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')