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


当前回答

使用“\ n”:

file.write("My String\n")

参考Python手册。

其他回答

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

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

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

f = open('test.txt', 'w')
f.write('test\n')

我真的不想每次都输入\n, @matthause的答案似乎不适合我,所以我创建了自己的类

class File():

    def __init__(self, name, mode='w'):
        self.f = open(name, mode, buffering=1)
        
    def write(self, string, newline=True):
        if newline:
            self.f.write(string + '\n')
        else:
            self.f.write(string)

这就是它的实现

f = File('console.log')

f.write('This is on the first line')
f.write('This is on the second line', newline=False)
f.write('This is still on the second line')
f.write('This is on the third line')

这应该在日志文件中显示为

This is on the first line
This is on the second lineThis is still on the second line
This is on the third line

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

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

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

更多关于字符串格式。