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:
with open('words.txt','r') as f:
for line in f:
for word in line.split('\n'):
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
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')