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


当前回答

使用“\ n”:

file.write("My String\n")

参考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'])

你可以在需要这种行为的特定地方装饰方法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')  

除非写入二进制文件,否则使用打印。下面的例子很适合格式化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的问题

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

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

你不需要添加\n!

对我来说,在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+"))