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


当前回答

使用“\ 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”:

file.write("My String\n")

参考Python手册。

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

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

更多关于字符串格式。

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

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

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