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


当前回答

请注意,该文件在Python 3中不支持,已被删除。你可以用open内置函数做同样的事情。

f = open('test.txt', 'w')
f.write('test\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'])

如果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_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")

通常你会使用\n,但无论出于什么原因,在Visual Studio Code 2019 Individual中它将无法工作。但是你可以用这个:

# Workaround to \n not working
print("lorem ipsum", file=f)  # Python 3.0 onwards only
print >>f, "Text"             # Python 2.0 and under

好的,这里有一个安全的方法。

with open('example.txt', 'w') as f:
 for i in range(10):
  f.write(str(i+1))
  f.write('\n')


这将在新行中对每个数字写入1到10。