每次调用file.write()时,我都想在字符串中添加换行符。在Python中最简单的方法是什么?


当前回答

为了支持多种操作系统的使用: 文件。写(f'some字符串和/或{variable}。{os.linesep}”)

其他回答

你可以通过两种方式做到这一点:

f.write("text to write\n")

或者,取决于你的Python版本(2或3):

print >>f, "text to write"         # Python 2.x
print("text to write", file=f)     # Python 3.x

如果你大量使用它(写了很多行),你可以子类化'file':

class cfile(file):
    #subclass file to have a more convienient use of writeline
    def __init__(self, name, mode = 'r'):
        self = file.__init__(self, name, mode)

    def wl(self, string):
        self.writelines(string + '\n')

现在它提供了一个额外的函数wl来做你想要的:

with cfile('filename.txt', 'w') as fid:
    fid.wl('appends newline charachter')
    fid.wl('is written on a new line')

也许我遗漏了一些东西,比如不同的换行符(\n, \r,…),或者最后一行也以换行符结束,但这对我来说是有效的。

你可以在需要这种行为的特定地方装饰方法write:

#Changed behavior is localized to single place.
with open('test1.txt', 'w') as file:    
    def decorate_with_new_line(method):
        def decorated(text):
            method(f'{text}\n')
        return decorated
    file.write = decorate_with_new_line(file.write)
    
    file.write('This will be on line 1')
    file.write('This will be on line 2')
    file.write('This will be on line 3')

#Standard behavior is not affected. No class was modified.
with open('test2.txt', 'w') as file:
        
    file.write('This will be on line 1')
    file.write('This will be on line 1')
    file.write('This will be on line 1')  

对我来说,在print()语句上使用append (a)和open()看起来更容易:

save_url  = ".\test.txt"

your_text = "This will be on line 1"
print(your_text, file=open(save_url, "a+"))

another_text = "This will be on line 2"
print(another_text, file=open(save_url, "a+"))

another_text = "This will be on line 3"
print(another_text, file=open(save_url, "a+"))

如果write是回调,则可能需要自定义writeln。

  def writeln(self, string):
        self.f.write(string + '\n')

本身在自定义打开器中。参见此问题的答案和反馈:在python 3中子类化文件对象(扩展打开和关闭操作)

(上下文管理器)

当我使用ftplib从“基于记录”(FB80)的文件中“检索行”时,我遇到了这个问题:

with open('somefile.rpt', 'w') as fp:
     ftp.retrlines('RETR USER.REPORT', fp.write)

最后得到一个没有换行符的长记录,这可能是ftplib的一个问题,但不清楚。

这就变成了:

with OpenX('somefile.rpt') as fp:
     ftp.retrlines('RETR USER.REPORT', fp.writeln) 

它起作用了。这是一些人正在寻找的用例。

完整的声明(只有最后两行是我的):

class OpenX:
    def __init__(self, filename):
        self.f = open(filename, 'w')

    def __enter__(self):
        return self.f

    def __exit__(self, exc_type, exc_value, traceback):
        self.f.close()

    def writeln(self, string):
        self.f.write(string + '\n')