Tariq Tariq - 3 years ago 124
Python Question

How to add line break in a text file after each word

I have a text file with this contents "one two three four" and I want to create a new text file with one word for each line, like this:


I came up with this code:

with open('words.txt','r') as f:
for line in f:
for word in line.split('\n'):
print word

It prints each word in new line, so my question how I can write these words in new file that have one word each line?

Answer Source

You're close to the proper answer but you need to split the line differently. for line in f already reads the file newline-by-newline. So just do a normal split to break the line using whitespace characters. This will usually split text files into words successfully.

You can handle multiple files in a with statement, which is very convenient for scripts like yours. Writing to a file is a lot like print with a few small differences. write is straightforward, but doesn't do newlines automatically. There's a couple other ways to write data to a file and seek through it, and I highly recommend you learn a bit more about them by reading the docs.

Below is your code with the changes applied. Be sure to take a look and understand why the changes were needed:

with open('words.txt','r') as f, open('words2.txt', 'w') as f2:
    for line in f:
       for word in line.split():
           f2.write(word + '\n')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download