【问题标题】:"ValueError: I/O operation on closed file" while writing to a file in a loop循环写入文件时出现“ValueError:对已关闭文件的 I/O 操作”
【发布时间】:2014-03-25 14:36:23
【问题描述】:

我必须将一个 file.txt 分成更多的文件。代码如下:

a = 0
b = open("sorgente.txt", "r")
c = 5
d = 16 // c
e = 1
f = open("out"+str(e)+".txt", "w")
for line in b:
    a += 1
    f.writelines(line)
    if a == d:
        e += 1
        a = 0
        f.close()
f.close()

所以,如果我运行它,它会给我这个错误:

todoController\WordlistSplitter.py", line 9, in <module>
    f.writelines(line)
ValueError: I/O operation on closed file

我知道如果您执行 for 循环,文件会关闭,因此我尝试将 f 放入 for 循环,但它不起作用,因为没有得到:

out1.txt
 1
 2
 3
 4

out2.txt
 5
 6
 7
 8

我只得到文件的最后一行。我该怎么办?有什么办法可以回忆起我之前定义的 open 函数?

【问题讨论】:

    标签: python file-io


    【解决方案1】:

    您在for 循环内f.close(),然后不要将open 新文件作为f,因此在下一次迭代时出错。您还应该使用with 来处理文件,这样您就无需显式地close 它们。

    由于您想一次向每个out 文件写入四行,您可以按如下方式进行:

    file_num = 0
    with open("sorgente.txt") as in_file:
        for line_num, line in enumerate(in_file):
            if not line_num % 4:
                file_num += 1
            with open("out{0}.txt".format(file_num), "a") as out_file:
                out_file.writelines(line)
    

    请注意,我使用变量名是为了更清楚地了解正在发生的事情。

    【讨论】:

      【解决方案2】:

      您关闭了文件,但没有中断 for 循环。

      【讨论】:

        【解决方案3】:

        如果 a == d 你正在关闭 f 然后稍后(在下一次迭代中)你试图写入它会导致错误。
        还有 - 你为什么要关闭 f 两次?

        【讨论】:

          【解决方案4】:

          您可能应该删除第一个f.close()

          a = 0
          b = open("sorgente.txt", "r")
          c = 5
          d = 16 // c
          e = 1
          f = open("out"+str(e)+".txt", "w")
          for line in b:
              a += 1
              f.writelines(line)
              if a == d:
                  e += 1
                  a = 0
                  # f.close()
          f.close()
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-09-27
            • 2016-07-21
            • 2015-07-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-12-18
            • 2016-08-26
            相关资源
            最近更新 更多