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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27726639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:11:06  来源:igfitidea点击:

Writing variables to new line of txt file in python

pythonstringfilevariablesappend

提问by Shane

From other posts, I've learned that '\n' signifies a new line when adding to a txt file. I'm trying to do just this, but I can't figure out the right syntax when an attribute is right before the new line.

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

My code I'm trying is like this:

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

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

As you can probably see, I'm trying to add the variable for each item in the list to a new line in a txt file. What's the correct way to do this?

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

采纳答案by Matt Smith

You just need to specify the newline character as a string:

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

Eg:

例如:

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

回答by Hackaholic

try this:

尝试这个:

att_file.write(attribute+"\n")

note :attribute must be some variable and must be string type

注意 :attribute 必须是某个变量并且必须是字符串类型

your code will look like this:

您的代码将如下所示:

with open("file.txt", "w") as att_file:
    for item in list:
        att_file.write(item+"\n")

withshould be before for, else every time you are opening file with write mode, it will omit the previous write

with应该是 before for,否则每次用写模式打开文件时,它会省略之前的写

回答by Alice

file7 = open('test_list7_file.txt','a')

file7 = open('test_list7_file.txt','a')

file7.write(var7 + '\n')

file7.write(var7 + '\n')

will work fine, BUT IF YOU APPEND TO EXISTINGtxt file the MOUSE CURSOR needs to be ONE SPACE AFTER THE LAST ENTRYwhen you save the file for use in your program.

会正常工作,但是如果您将文件附加到现有的txt 文件,则当您保存文件以在程序中使用时,鼠标光标需要位于最后一个条目之后的一个空格处

~no space and it joins the last entry,

~没有空格,它加入了最后一个条目,

~on the next line already when you create you file to be added to, it adds an empty line first

〜在您创建要添加的文件时的下一行,它首先添加一个空行