小编典典

csv编写器未关闭文件

python

即时通讯读取一个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?


阅读 215

收藏
2020-12-20

共1个答案

小编典典

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)
2020-12-20