Error handling 尝试从文本文件中提取特定的数据行并创建新的输出文本文件

Error handling 尝试从文本文件中提取特定的数据行并创建新的输出文本文件,error-handling,Error Handling,我的代码不断出现这个错误 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&q

我的代码不断出现这个错误

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

您的问题是
fout.close()
。您在每次迭代中通过
for
循环运行它,导致在写入第一行后关闭fout。因为您正在使用
与。。。作为fout
您实际上根本不需要
fout.close()
。只要去掉那条线,你就应该很好了