Skip to content Skip to sidebar Skip to footer

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. I'm trying to do just this, but I can't figure out the right syntax when an attribute is ri

Solution 1:

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

Eg:

withopen("file.txt", "w") as att_file:
    for item inlist:
        att_file.write(attribute + "\n")

Solution 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:

withopen("file.txt", "w") as att_file:
    for item inlist:
        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

Solution 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

Post a Comment for "Writing Variables To New Line Of Txt File In Python"