-2

My question is: How can I write lists in a file?

So:

list = ["damn","bro"]
correct_list = "\n".join(list)
file = open("test.txt", "w")

How do I write this into a file now that it's a list? So in the file:

damn
bro

I already tried it but it just stand behind each other without whitespace

Lucas
  • 144
  • 1
  • 12
  • Do you want to know how to read from a file and store it as a list or take all the elements of a list and write them to a file? – Buzz Jan 11 '17 at 20:47
  • @Buzz I want to take all elements of a list and write them to a file. – Lucas Jan 11 '17 at 20:49
  • 1
    the solution linked to above is wrong, the OP tries to write into a file and not read from a file. I've flagged this question so hopefully the duplicate link is removed – hansaplast Jan 11 '17 at 20:50
  • @Lucas in your code there's a line missing where you actually write into the file. it should read `file.write(correct_list)`. With this it works. – hansaplast Jan 11 '17 at 20:51
  • also: `list` is a reserved python keyword, you should not name your variable like this as you might into problems later, try `l` for example – hansaplast Jan 11 '17 at 20:54
  • Possible duplicate of [Writing a list to a file with Python](http://stackoverflow.com/questions/899103/writing-a-list-to-a-file-with-python) – SiHa Jan 12 '17 at 09:54

1 Answers1

0

First, you probably shouldn't use list because it is a reserved word in python.(link) You could use almost anything else. I usually use lst

You need to actually put it in the file. Your code is missing:

file.write(correct_list)

this will actually write the string to the file.

You can also try something like this:

lst=["damn","bro"]
file = open("test.txt", "w")
for item in lst:
    file.write(item+"\n")

This will loop over each item in the list and write them one at a time to the file with a new line at the end

Also make sure you close the file when you are done with it:

file.close()
Buzz
  • 1,751
  • 20
  • 24