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


当前回答

如果你大量使用它(写了很多行),你可以子类化'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,…),或者最后一行也以换行符结束,但这对我来说是有效的。

其他回答

使用“\ n”:

file.write("My String\n")

参考Python手册。

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, @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

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

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

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

你不需要添加\n!