python - 如何删除文本文件中的特定行而不留下空行?
问题描述
我的代码:
with open("file_name.txt", "r") as f:
lines = f.readlines()
with open("file_name.txt", "w") as f:
for line in lines:
if line.strip("\n") != thing_to_be_deleted:
f.write(line)
问题是这会在文件中留下一个空行。
解决方案
当您使用 readlines() 方法时,您将文件转换为列表,其中文件的每一行都是列表中的一个值。因此,您可以使用列表方法来管理该文件内容。具体来说,该remove()
方法将对您有所帮助。例子:
with open("file_name.txt", "r") as f:
lines = f.readlines()
line_to_delete = f'{thing_to_be_deleted}\n'
while line_to_delete in lines:
lines.remove(line_to_delete)
with open("file_name.txt", "w") as f:
for line in lines:
f.write(line)
推荐阅读
- cookies - 通过 Cloudflare 代理将 Cookie 从客户端传递到负载均衡器
- java - Hibernate QuerySyntaxException 表未映射
- java - java中的特定日期格式
- java - dynamodb getitem android
- android - 测试列表偏好
- c# - 下一个按钮仅向上移动一条记录,下一次单击不起作用(C#)
- visual-studio - 私有包:是在调试模式下编译项目所必需的调试文件
- javascript - 为什么javascript在部署时不呈现任何功能
- elasticsearch - 更新 Elasticsearch 中现有索引的映射
- android - NoClassDefFoundError for Guava 的 ImmutableMap with Dagger 2 for Android