3

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:

one
two
three
four 

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?

Tariq
  • 93
  • 1
  • 13
  • what's the difference between "each word in new line" and "one word each line"? seems like your code does that and is what you're looking for – chickity china chinese chicken Oct 01 '17 at 09:00
  • what i am trying to do, is to create text file that have one column, and each line have just one word form the old file – Tariq Oct 01 '17 at 09:03
  • 1
    Possible duplicate of [Correct way to write line to file in Python](https://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file-in-python) – user8153 Oct 01 '17 at 09:08

1 Answers1

2

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')
Aaron3468
  • 1,734
  • 16
  • 29