我正在尝试使用python进行一些数据清理。我有一些大的(1 - 2gigs) csv
文件,我想按一些属性(例如日期,时间)排序,然后输出另一个csv
文件与此信息,目的是使它能够在Excel中使用。
当我遍历行时,我遇到了一些重要的内存问题。最初我使用的是32位空闲,它不会运行我的代码,然后切换到64-bit Spyder
。现在代码运行了,但是在第一个迭代行停止(看起来处理,内存被消耗,但是在最后半小时没有看到它继续前进)。
我的代码如下。该过程在第10行停止(突出显示)。我对python很陌生,所以我确信我的代码非常原始,但它是我能做的最好的!感谢您提前的帮助:)
def file_reader(filename):
"function takes string of file name and returns a list of lists"
global master_list
with open(filename, 'rt') as csvfile:
rows = []
master_list = []
rowreader = csv.reader(csvfile, delimiter=',', quotechar='|')
**for row in rowreader:**
rows.append(','.join(row))
for i in rows:
master_list.append(i.replace(' ', '').replace('/2013', ',').split(","))
return master_list
def trip_dateroute(date,route):
dateroute_list = []
for i in master_list:
if str(i[1]) == date and str(i[3]) == route:
dateroute_list.append(i)
return dateroute_list
def output_csv(filename, listname):
with open(filename, "w") as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar='|', lineterminator='\n')
for i in listname:
writer.writerow(i)
答案 0 :(得分:0)
如果您不需要将整个文件内容保存在内存中,则只需处理每一行并立即将其写入输出文件即可。此外,在您的示例中,您解析CSV然后再次生成CSV,但您似乎没有使用已解析的数据。如果这是正确的,你可以这样做:
def file_converter(infilename, outfilename):
with open(infilename, 'rt') as infile, open(outfilename, "w") as outfile:
for line in infile:
line.replace(' ', '').replace('/2013', ',')
outfile.write(line)
如果使用函数trip_dateroute()
来过滤实际应该写出的行,你也可以添加它,但是你实际上必须解析CSV:
def filter_row(row, date, route):
return str(row[1]) == date and str(row[3]) == route
def cleanup(field):
return field.replace(' ', '').replace('/2013', ',')
def file_converter(infilename, outfilename, date, route):
with open(infilename, 'rt') as infile, open(outfilename, "w") as outfile:
reader = csv.reader(infile, delimiter=',', quotechar='|')
writer = csv.writer(outfile, delimiter=',', quotechar='|', lineterminator='\n')
for row in reader:
row = [cleanup(field) for field in row if filter_row(row, date, route)]
writer.writerow(row)