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


当前回答

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

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

更多关于字符串格式。

其他回答

你可以这样做:

file.write(your_string + '\n')

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

file.write(your_string)
file.write("\n")

注意,写操作是被缓冲的,所以两者是一样的。

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

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

对我来说,在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'some字符串和/或{variable}。{os.linesep}”)

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

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

更多关于字符串格式。