1

so my question is simple, how can I write my list in a text file in a form list. (See the code bellow to understand what I mean). Thanks you

addlist.py

data = []
#List data
data.append("Test1")
data.append("Test2")

#Send list to files.
with open("newlist.txt", "w") as f:
    for item in data:
        f.write("%s\n" % item)

So when I run this code, it write the data in my txt files but not as a list. I want the data in a list.

newlist.txt

Test1
Test2
tiberhockey
  • 323
  • 2
  • 11
  • Show what you expect to be written to the file. – Scott Hunter Feb 27 '20 at 16:16
  • 1
    "I want the data '*in a list*'" What do you mean by '*in a list*' in this context? Enclosed by square brackets and separated by commas? Just write an open square bracket at the start and a comma after each line except the last and a close square bracket at the end... – JMoravitz Feb 27 '20 at 16:17
  • **Please clarify your question.** Both the comments above are good, and have been completely ignored. – AMC Feb 27 '20 at 18:15
  • Does this answer your question? [Writing a list to a file with Python](https://stackoverflow.com/questions/899103/writing-a-list-to-a-file-with-python) – AMC Feb 27 '20 at 18:16
  • I tried to edit the title of this post to something slightly more accurate/correct, but I was unable to submit it because SO detects that this is a duplicate. – AMC Feb 27 '20 at 18:17

2 Answers2

1

you can use:

with open("newlist.txt", "w") as f:
    f.write(str(data))

you are writing in the file exactly what you get when you use print(data)

kederrac
  • 15,339
  • 4
  • 25
  • 45
0

I think that what you want is that the output is in JSON format. For that try this:

import json

f.write(json.dumps(data))
rdnobrega
  • 421
  • 5
  • 12