每次调用file.write()时,我都想在字符串中添加换行符。在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

你可以这样做:

file.write(your_string + '\n')

正如另一个答案所建议的,但为什么在可以调用文件时使用字符串连接(缓慢,容易出错)。写两次:

file.write(your_string)
file.write("\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。

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

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

更多关于字符串格式。