温馨提示×

Python writelines函数怎样添加换行

小樊
218
2024-07-20 08:43:48
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Python中,可以使用 write() 函数来添加换行, 例如:

file = open("example.txt", "w")
file.write("hello\n")
file.write("world\n")
file.close()

另外,也可以在 writelines() 函数中传入包含换行符的字符串列表,例如:

file = open("example.txt", "w")
lines = ["hello\n", "world\n"]
file.writelines(lines)
file.close()

无论是使用 write() 还是 writelines(),都可以在字符串中加入 \n 来添加换行。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:Python writelines函数为何不直接写入

0