【发布时间】:2019-03-28 14:42:11
【问题描述】:
我无法将单词打印到文件中。我的代码只是给我一个错误:
cwriter = outfile.write(line) ValueError: I/O operation on closed file
import collections
wordcount = collections.Counter()
with open('./tekst1.txt') as infile, open('tekst2.txt', 'w') as outfile:
for line in infile:
wordcount.update(line.split())
for k,v in wordcount.iteritems():
outfile.write(line)
【问题讨论】:
-
你能缩进你的代码吗?该问题可能与
outfile.write(line)不在with open(...) as outfile:的“范围”内有关。 -
如果您想写信给
outfile,您必须在with语句完成之前这样做。缩进for循环。
标签: python python-2.7