如何使用open在python中过滤数据文件并创建新文件?
我有巨大的csv,我试图用open过滤数据 我知道我可以在命令行上使用FINDSTR,但我想使用python创建一个新的过滤文件,或者我想创建一个数据帧作为输出 这是我的密码:如何使用open在python中过滤数据文件并创建新文件?,python,pandas,csv,bigdata,data-warehouse,Python,Pandas,Csv,Bigdata,Data Warehouse,我有巨大的csv,我试图用open过滤数据 我知道我可以在命令行上使用FINDSTR,但我想使用python创建一个新的过滤文件,或者我想创建一个数据帧作为输出 这是我的密码: outfile = open('my_file2.csv', 'a') with open('my_file1.csv', 'r') as f: for lines in f: if '31/10/2018' in lines: print(lines)
outfile = open('my_file2.csv', 'a')
with open('my_file1.csv', 'r') as f:
for lines in f:
if '31/10/2018' in lines:
print(lines)
outfile.write(lines)
问题是生成的输出文件=输入文件,并且没有过滤器(文件大小相同)
多亏了所有的代码的问题在于最后一行的缩进。它应该在if语句中,因此只有包含
'31/10/2018'
的行才能被写入
outfile = open('my_file2.csv', 'a')
with open('my_file1.csv', 'r') as f:
for lines in f:
if '31/10/2018' in lines:
print(lines)
outfile.write(lines)
要使用Pandas进行筛选并创建数据帧,请执行以下操作:
import pandas as pd
import datetime
# I assume here that the date is in a seperate column, named 'Date'
df = pd.read_csv('my_file1.csv', parse_dates=['Date'])
# Filter on October 31st 2018
df_filter = df[df['Date'].dt.date == datetime.date(2018, 10, 31)]
# Output to csv
df_filter.to_csv('my_file2.csv', index=False)
(对于非常大的csv,请查看pd.read\u csv()
参数“chunksize”)
要将open(..)用作f:,可以执行以下操作:
import pandas as pd
filtered_list = []
with open('my_file1.csv', 'r') as f:
for lines in f:
if '31/10/2018' in lines:
print(lines)
# Split line by comma into list
line_data = lines.split(',')
filtered_list.append(line_data)
# Convert to dataframe and export as csv
df = pd.DataFrame(filtered_list)
df_filter.to_csv('my_file2.csv', index=False)
接近输入错误:您只需将
缩进文件外。写入(行)
与打印(行)
相同。谢谢。您知道如何在不创建新文件的情况下使用熊猫数据帧中的过滤数据吗?或者我如何用我的代码按列过滤数据?请参见上面的编辑。好的,谢谢,但我指的是:with open('my_file1.csv','r')作为f:的输出,用于f:if'31/10/2018'中的行:line:print(行)中的行:如果您仍要使用Pandas,为什么要这样做?或者'my_file1.csv'
除了标题和数据行之外是否还包含其他行?因为文件太大,我只想分析通过打印获得的输出(行)。我不知道为什么,但是输出文件(my_file2.csv)缺少10行