Home > Software design >  Issue when trying to save each item in a list to a text file
Issue when trying to save each item in a list to a text file

Time:10-24

I'm trying to save each item in a list to a text file, however, I keep coming across an error.

This is an example of my code:

example_list = ["1", "2", "3"]

for i in example_list:
    with open("file.txt", "w") as f:
        f.write(i)

When I run this and then open file.txt all that's in there is "3".

CodePudding user response:

Answering your question

example_list = ["1", "2", "3"]
for i in example_list:
    with open("file.txt", "a") as f: # change mode to append
        f.write(i)

Little better solution

example_list = ["1", "2", "3"]
with open("file.txt", "w") as f: # open file once
    f.write("".join(example_list))

CodePudding user response:

Use append mode to write to next time so it will not overide existing file content

  • Related