Python csv writer没有关闭文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3347775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
csv writer not closing file
提问by l--''''''---------''''''''''''
im reading a csv file and then writing a new one:
我正在读取一个 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)
for some reason i cannot get the csv.writer to close the file. when i open the file it opens it as READ ONLY because it says that is still open.
由于某种原因,我无法让 csv.writer 关闭文件。当我打开文件时,它以只读方式打开它,因为它说它仍然是打开的。
how do i close thefile_subset1.csv after i am done with it?
完成后如何关闭 thefile_subset1.csv?
采纳答案by John La Rooy
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)
回答by Donald Miner
You can break out the open command into its own variable, so that you can close it later.
您可以将 open 命令分解为它自己的变量,以便以后可以关闭它。
f = open('/pythonwork/thefile_subset1.csv', 'w')
writer = csv.writer(f)
f.close()
csv.writerthrows a ValueErrorif you try to write to a closed file.
csv.writerValueError如果您尝试写入已关闭的文件,则抛出 a 。
回答by James Roth
Force the writer to clean up:
强制写入器清理:
del writer
回答by pillmuncher
Look at the difference:
看看区别:
with open('thefile.csv', 'rb') as f:
data = list(csv.reader(f))
vs:
对比:
writer = csv.writer(open('/pythonwork/thefile_subset1.csv', 'w'))
回答by Jim Clouse
close the file, not the csv writer. To do this, you'll need to open the file first before instantiating your writer rather than keeping it all in one line.
关闭文件,而不是 csv writer。为此,您需要在实例化编写器之前先打开文件,而不是将其全部保留在一行中。
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()
Also, I would suggest keeping your imports at the top of the script and closing the first file when you're done with it.
另外,我建议将您的导入保留在脚本的顶部,并在完成后关闭第一个文件。

