save Python list to a txt file in nice order [duplicate]
I have a file that is like this:
word, number
word, number
[...]
and I want to take/keep just the words, again one word in new line
word
word
[...]
My code so far
f = open("new_file.txt", "w")
with open("initial_file.txt" , "r+") as l:
for line in l:
word = line.split(", ")[0]
f.write(word)
print word # debugging purposes
gives me all the words in one line in the new file
wordwordwordword[...]
Which is the pythonic and most optimized way to do this?
I tried to use f.write("\n".join(word))
but what I got was
wordw
ordw
[...]
You can just use f.write(str(word)+"\n")
to do this. Here str
is used to make sure we can add "\n".
If you're on Windows, it's better to use "\r\n"
instead.