如何避免在文件末尾换行?

时间:2021-06-10 19:57:24

标签: python file split

我需要使用

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

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

1 个答案:

答案 0 :(得分:1)

请重新表述您的问题,因为它不是很清楚。

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

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