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", "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 在编写第一行后关闭。由于您正在使用,因此with ... as fout
您实际上根本不需要fout.close()
。只需删除那条线,你应该会很好。
推荐阅读
- c# - IsVisible 在 ListView 中未正确加载
- exiftool - exiftool 是否需要完整的文件来提取元数据
- java - 您如何断言 `Collection` 的`Collection` 包含包含某些元素的元素?
- aspectj-maven-plugin - AspectJ maven 插件编译时内存超出错误
- angular - 调用函数清除按钮 ej2Multiselect Syncfusion Angular 到按钮事件
- php - 在 PHP 中以引导模式形式显示动态内容
- scala - 如何根据 Spark Scala 中的值将行数据转置/旋转到不同的列?
- excel - 如何通过 MS Excel VBA 修改 Word 中的纯文本内容控件
- customization - 在 FAR 管理器中按日期对文件进行排序
- php - 如何在 DB raw Laravel 中使用数组的值