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


当前回答

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

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

你不需要添加\n!

其他回答

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")

你可以使用:

file.write(your_string + '\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

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

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

你不需要添加\n!

为了支持多种操作系统的使用: 文件。写(f'some字符串和/或{variable}。{os.linesep}”)