首页 > 解决方案 > 如何避免文件末尾的新行?

问题描述

我需要使用

for line in doc.split('\n'):

并在每一行上做一些操作,但我在文件的末尾得到了空行,因为我认为它每次都会拆分一个新行!我怎样才能避免这个问题?

标签: pythonfilesplit

解决方案


请改写您的问题,因为它不是很清楚。

无论如何,如果您正在使用文本文件,您可以使用:

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

推荐阅读