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


当前回答

另一个解决方案是使用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'])

其他回答

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")

除非写入二进制文件,否则使用打印。下面的例子很适合格式化csv文件:

def write_row(file_, *columns):
    print(*columns, sep='\t', end='\n', file=file_)

用法:

PHI = 45
with open('file.csv', 'a+') as f:
    write_row(f, 'header', 'phi:', PHI, 'serie no. 2')
    write_row(f)  # additional empty line
    write_row(f, data[0], data[1])

您还可以使用partial作为一种更python化的方式来创建这种包装器。在下面的例子中,用预定义的kwargs打印行。

from functools import partial


with open('file.csv', 'a+') as f:
    row = partial(print, sep='\t', end='\n', file=f)

    row('header', 'phi:', PHI, 'serie no. 2', end='\n\n')
    row(data[0], data[1])

注:

打印文档 “{},{}”。format(1, 'the_second') - https://pyformat.info/, PEP-3101 '\t' -制表符 函数定义中的*列-将任意数量的参数分派到列表-参见关于*args和**kwargs的问题

你可以使用c风格的字符串格式化:

file.write("%s\n" % "myString")

更多关于字符串格式。

实际上,当你使用多行语法时,就像这样:

f.write("""
line1
line2
line2""")

你不需要添加\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