在Python中,换行写入文件可以通过以下几种方法实现:
1. 使用换行符 `\n`:
filename = "data.txt"
with open(filename, "w") as file:
file.write("Hello, world!\n")
2. 使用 `print` 函数,它会自动在输出结束时添加换行符:
filename = "data.txt"
with open(filename, "w") as file:
print("Hello, world!", file=file)
3. 使用 `write` 方法后跟换行符 `\n`:
filename = "data.txt"
with open(filename, "w") as file:
file.write("Hello, world!\n")
4. 使用 `format` 方法插入换行符:
filename = "data.txt"
with open(filename, "w") as file:
file.write("{}
".format("Hello, world!"))
5. 使用 `f-string`(Python 3.6+):
filename = "data.txt"
with open(filename, "w") as file:
file.write(f"Hello, world!
")
以上方法都可以实现在文件中换行写入数据。请选择适合您需求的方法