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


当前回答

如果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')

其他回答

如果你大量使用它(写了很多行),你可以子类化'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')  
file_path = "/path/to/yourfile.txt"
with open(file_path, 'a') as file:
    file.write("This will be added to the next line\n")

or

log_file = open('log.txt', 'a')
log_file.write("This will be added to the next line\n")

你可以使用:

file.write(your_string + '\n')

另一个解决方案是使用fstring从列表中写入

lines = ['hello','world']
with open('filename.txt', "w") as fhandle:
  for line in lines:
    fhandle.write(f'{line}\n')

作为一个函数

def write_list(fname, lines):
    with open(fname, "w") as fhandle:
      for line in lines:
        fhandle.write(f'{line}\n')

write_list('filename.txt', ['hello','world'])