Writing variables to new line of txt file in python

我的未来我决定 提交于 2019-12-31 04:01:11

问题


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.

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?


回答1:


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



回答2:


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




回答3:


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

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.

~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



来源:https://stackoverflow.com/questions/27726639/writing-variables-to-new-line-of-txt-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!