即时通讯读取一个csv文件,然后编写一个新文件:
import csv with open('thefile.csv', 'rb') as f: data = list(csv.reader(f)) import collections counter = collections.defaultdict(int) for row in data: counter[row[11]] += 1 writer = csv.writer(open('/pythonwork/thefile_subset1.csv', 'w')) for row in data: if counter[row[11]] >= 500: writer.writerow(row)
由于某种原因,我无法使csv.writer关闭文件。当我打开文件时,它以只读状态打开,因为它说仍然打开。
完成后如何关闭thefile_subset1.csv?
with open('/pythonwork/thefile_subset1.csv', 'w') as outfile: writer = csv.writer(outfile) for row in data: if counter[row[11]] >= 500: writer.writerow(row)