【问题标题】:How to fix I/O operation on closed file error?如何修复关闭文件错误的 I/O 操作?
【发布时间】: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


【解决方案1】:

问题是您在with 语句已经关闭它之后尝试写入outfile。缩进 for 循环可以解决问题。

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("{}: {}".format(k, v))  # For example

但是,似乎没有任何理由同时打开这两个文件。 wordcount 不以任何方式限定于with 语句,因此它的值从一个with 持续到下一个。

import collections


wordcount = collections.Counter()

with open('./tekst1.txt') as infile:
     for line in infile:
        wordcount.update(line.split())

with open('tekst2.txt', 'w') as outfile:
    for k,v in wordcount.iteritems():
        outfile.write("{}: {}".format(k,v))

【讨论】:

  • 它可以工作,但我得到一个行数相同的空文件。我要做的是创建一个脚本,列出 tekst1 文件的字数。而是将其打印在屏幕上,它基本上会将其输出到 tekst2。
  • 所以,您在对outfile.write 的调用中使用了line,而不是来自wordcount 的值。你想要像outfile.write("{}: {}".format(k, v)) 这样的东西吗?
  • 非常感谢先生。这就是我一直在寻找的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多