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

Remove newline at the end of a file in python

我正在修改一个 python 的文件,该文件可能已经包含如下换行符:

#comment
something

#new comment
something else

我的代码向该文件附加了一些行,我还在编写将删除我添加的内容的代码(如果文件中发生其他修改,理想情况下也能正常工作)。

目前,我最终得到的文件每次应用代码 (append/remove) 时都会增长,文件末尾有换行符。

我正在寻找一种干净的方法来删除这些换行符,而不需要过多的编程复杂性。文件“内部”的换行符应该保留,文件末尾的换行符应该被删除。

使用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()