首页 > 解决方案 > 尝试从文本文件中提取特定数据行并创建新的输出文本文件

问题描述

我的代码不断出现此错误

fout.write(line)  #writing in the data
ValueError: I/O operation on closed file.

代码

with open("READ.txt") as fin:  #opening the input files (text file)
  lines = fin.readlines() #reading lines by line
with open("out.txt", "w") as fout: #opening the output files
                 for line in lines[20:62289]:  #selecting just the lines you need
                     fout.write(line)  #writing in the data
                     fout.close()  #ensure you close to save the file and it data

标签: error-handling

解决方案


你的问题是fout.close()。您在for循环中的每次迭代都运行它,导致 fout 在编写第一行后关闭。由于您正在使用,因此with ... as fout您实际上根本不需要fout.close()。只需删除那条线,你应该会很好。


推荐阅读