简体   繁体   English

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

[英]Writing variables to new line of txt file in python

From other posts, I've learned that '\\n' signifies a new line when adding to a txt file. 从其他帖子中,我了解到“ \\ n”表示添加到txt文件时的换行符。 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. 我正在尝试执行此操作,但是当属性恰好在新行之前时,我无法找出正确的语法。

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. 您可能会看到,我正在尝试将列表中每个项目的变量添加到txt文件的新行中。 What's the correct way to do this? 正确的方法是什么?

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")

try this: 尝试这个:

att_file.write(attribute+"\n")

note :attribute must be some variable and must be string type 注意:属性必须是一些变量,并且必须是字符串类型

your code will look like this: 您的代码将如下所示:

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

with should be before for , else every time you are opening file with write mode, it will omit the previous write with应该在for之前,否则每次使用写入模式打开文件时,它将忽略之前的写入

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

file7.write(var7 + '\\n') file7.write(var7 +'\\ n')

will work fine, BUT IF YOU APPEND TO EXISTING txt file the MOUSE CURSOR needs to be ONE SPACE AFTER THE LAST ENTRY when 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 〜在创建要添加到的文件时已经在下一行上,它将首先添加一个空行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM