简体   繁体   English

删除 python 中文件末尾的换行符

[英]Remove newline at the end of a file in python

I'm modifying a file with python that may already contain newlines like the following:我正在使用 python 修改一个文件,该文件可能已经包含如下换行符:

#comment
something

#new comment
something else

My code appends some lines to this file, I'm also writing the code that will remove what I added (ideally also working if other modifications occurred in the file).我的代码在该文件中附加了一些行,我还在编写将删除我添加的代码的代码(如果文件中发生其他修改,理想情况下也可以工作)。

Currently, I end up with a file that grows each time I apply the code (append/remove) with newlines characters at the end of the file.目前,每次我在文件末尾使用换行符应用代码(追加/删除)时,我都会得到一个文件。

I'm looking for a clean way to remove those newlines without too much programmatic complexity.我正在寻找一种干净的方法来删除这些换行符,而不需要太多的程序复杂性。 Newlines "inside" the file should remain, newlines at the end of the file should be removed.文件“内部”的换行符应该保留,文件末尾的换行符应该被删除。

use str.rstrip() method:使用str.rstrip()方法:

my_file =  open("text.txt", "r+")
content = my_file.read()
content = content.rstrip('\n')
my_file.seek(0)

my_file.write(content)
my_file.truncate()
my_file.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM