【问题标题】:How can i avoid new line at the end of the file?如何避免文件末尾的新行?
【发布时间】:2021-06-10 19:57:24
【问题描述】:

我需要使用

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

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

【问题讨论】:

  • 您是在问如何避免doc 在末尾包含一个空行吗?
  • 只需打开文件并一次读取一行。 with open(fname) as f: for line in f.read()。请参阅 Riccardo 的回答。

标签: python file split


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多