antonis_man
antonis_man

Reputation: 311

How to write in new line in file in Python

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
[...]

Upvotes: 6

Views: 24277

Answers (1)

ForceBru
ForceBru

Reputation: 44886

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.

Upvotes: 11

Related Questions