csv writer没有关闭文件

时间:2010-07-27 20:41:13

标签: python csv

我正在阅读一个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关闭文件。当我打开文件时,它只打开它,因为它说它仍然是打开的。

如何在完成后关闭file_subset1.csv?

5 个答案:

答案 0 :(得分:22)

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)

答案 1 :(得分:19)

您可以将open命令分解为自己的变量,以便稍后关闭它。

f = open('/pythonwork/thefile_subset1.csv', 'w')
writer = csv.writer(f)
f.close()
如果您尝试写入已关闭的文件,

csv.writer会抛出ValueError

答案 2 :(得分:5)

关闭文件,而不是csv编写器。为此,您需要在实例化编写器之前先打开文件,而不是将其全部保存在一行中。

import csv
import collections

with open('thefile.csv', 'rb') as f:
    data = list(csv.reader(f))

counter = collections.defaultdict(int)
for row in data:
    counter[row[11]] += 1

f.close()  # good idea to close if you're done with it

fSubset = open('/pythonwork/thefile_subset1.csv', 'w')
writer = csv.writer(fSubset)
for row in data:
    if counter[row[11]] >= 500:
        writer.writerow(row)

fSubset.close()

另外,我建议您将导入保留在脚本的顶部,并在完成后关闭第一个文件。

答案 3 :(得分:4)

强制撰稿人清理:

del writer

答案 4 :(得分:0)

看看区别:

with open('thefile.csv', 'rb') as f:
    data = list(csv.reader(f))

VS

writer = csv.writer(open('/pythonwork/thefile_subset1.csv', 'w'))