python - 如何避免文件末尾的新行?
问题描述
我需要使用
for line in doc.split('\n'):
并在每一行上做一些操作,但我在文件的末尾得到了空行,因为我认为它每次都会拆分一个新行!我怎样才能避免这个问题?
解决方案
请改写您的问题,因为它不是很清楚。
无论如何,如果您正在使用文本文件,您可以使用:
with open("path_to_soruce_textfile", "r") as src, open("path_to_dest_textfile", "w") as dst:
for line in src.readlines(): # this gives you a list of lines with each line finishing with \n
processed_line = modidy(line)
dst.write(processed_line) # make sure \n is at the end of each line when you write
# the file is automatically closed
推荐阅读
- flask - flask - 显示来自 SQL Server 的列表
- javascript - 使用 ReactJS 具有相同的价格和总计列值
- java - 在 SupportPlaceAutocompleteFragment 中搜索新地点后 Map Fragment 循环回当前位置
- javascript - ajax、javascript、php 无法正常工作
- c# - C# ITypeInfo.GetContainingTypeLib 在传递 VBA 类的实时实例时失败
- ruby-on-rails - Rails 从通过神社上传到文章中的文章中调用图像
- mysql - 尝试将节点添加到 MySQL Innodb 集群
- android - 在linearLayout(android kotlin)的工具栏顶部放置一个按钮
- c# - 身份服务器在 /connect/authorize/callback 中一直显示“显示登录:用户未通过身份验证”
- ruby-on-rails - 如何使用命名空间控制器 rails 5.2 显示数据