每次调用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")

你可以这样做:

file.write(your_string + '\n')

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

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

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

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

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

更多关于字符串格式。

好的,这里有一个安全的方法。

with open('example.txt', 'w') as f:
 for i in range(10):
  f.write(str(i+1))
  f.write('\n')


这将在新行中对每个数字写入1到10。

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

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