如何在 Python 中的字符串中指示换行符,以便可以将多行写入文本文件?
要在字符串中指定新行,可以使用换行符\n。在 Python 中将包含以下内容的字符串写入\n文件时,它将在文件中出现换行符的位置创建新行。
\n
以下是如何将多行写入文件的方法:
# Example string with newlines text = "This is the first line.\nThis is the second line.\nThis is the third line." # Open a file in write mode with open('output.txt', 'w') as file: # Write the string to the file file.write(text)
text
output.txt
open()
with
file.write(text)
如果您有多个字符串(例如,存储在列表中),则可以使用write()或将每个字符串写在新行上writelines()。
write()
writelines()
lines = ["This is the first line.", "This is the second line.", "This is the third line."] # Open the file in write mode with open('output.txt', 'w') as file: # Write each line with a newline character for line in lines: file.write(line + '\n')
这两种方法都会导致将多行写入文件output.txt。