在python中将变量写入txt文件的新行

Sha*_*ane 2 python string variables file append

从其他帖子中,我了解到 '\n' 在添加到 txt 文件时表示换行。我正在尝试这样做,但是当属性正好位于新行之前时,我无法找出正确的语法。

我正在尝试的代码是这样的:

for item in list:
    with open("file.txt", "w") as att_file:
        att_file.write(variable\n)
Run Code Online (Sandbox Code Playgroud)

您可能会看到,我正在尝试将列表中每个项目的变量添加到 txt 文件中的新行中。这样做的正确方法是什么?

Mat*_*ith 7

您只需要将换行符指定为字符串:

例如:

with open("file.txt", "w") as att_file:
    for item in list:
        att_file.write(attribute + "\n")
Run Code Online (Sandbox Code Playgroud)