在Python中,写入文件时可以使用换行符,通常有两种方式:
1. 使用 `\n` 作为换行符。
2. 使用 `\r\n` 作为换行符(特别是在Windows系统中)。
filename = "data.txt" 文件名
with open(filename, "w") as file: 打开文件
file.write("Hello, world!\n") 写入数据,后面跟换行符
使用 `\r\n` 进行换行的示例代码:
filename = "data.txt" 文件名
with open(filename, "w") as file: 打开文件
file.write("Hello, world!\r\n") 写入数据,后面跟换行符
使用 `with` 语句可以确保文件在使用完毕后自动关闭。