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


当前回答

你可以使用:

file.write(your_string + '\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'some字符串和/或{variable}。{os.linesep}”)

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

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

更多关于字符串格式。

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

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