简体   繁体   中英

How to read a text file and write it word by word into another file in python?

I have a text file like this :

this is a text file.

I want to save it into another file like this:

this
is
a
text
file

Each word comes into new line. I also have this very simple code :

with open("test.txt", encoding = 'utf-8') as f:
    for line in f:
        for word in line.split():
            print(word)
            with open("test1.txt","a") as f1:
                f1.write(word)

But after printing, all the words will write stick together. can you give me a hand? (just a little hint what should I do)

When you do:

for word in line.split():

Actually you are iterating through this list:

['this', 'is', 'a', 'text', 'file.']

Because you split over whitespaces. Then when you wrote it back to "test1.txt","a" , you are writing what's in that list all together without any delimiter or space, so this is your output:

thisisatextfile.

Now, if you want every word on each line, just write each word concatenated with "\\n" , (new line character).

I've made some changes to your code, should look like this:

with open("test.txt", 'r') as f, open("test1.txt", 'w') as f1:
    for line in f:
        f1.write('\n'.join(line.split()))
        f1.write('\n')

Let's thave a closer look on the most important line: f1.write('\\n'.join(line.split())) .

  • str.split() will split a string into a list at white space character(s). (tab(s), space(s), newline(s)). So the result of 'word1 word2\\nword3\\tword4'.split() will be ['word1', 'word2', 'word3', 'word4'] .

  • str.join(<iterable>) joins an iterable with the given string together. The result of '\\n'.join(['word1', 'word2', 'word3', 'word4']) is 'word1\\nword2\\nword3\\nword4'

This simple script should solve your problem:

 f=open("test.txt")
 fw=open("test1.txt", 'w')
 for line in f.readlines():
     for word in line.split(" "):
         print(word)
         fw.write(word+"\n")
 fw.close()

You should open your output file only once.

with open("test.txt", encoding = 'utf-8') as f:
    with open("test1.txt","w") as f1:
        for line in f:
            for word in line.split():
                print(word)
                f1.write(word + '\n')

But if you want to stick with your solution, just add + '\\n' after word . This will create a line break after the words you add to the file.

write don't write anything you don't tell it to write, so you have to tell it that write a new line "\\n" explicitly. Alternatively you can use the print function that automatically put the new line, to get the desire result like this:

print(word,file=f1)

that is in python 3, in python 2 is

print >>f1, word

in your case that would be

with open("test.txt") as f, open("test1.txt","a") as f1:
    for line in f:
        temp="\n".join(line.split())
        print(temp)
        print(temp,file=f1)

that way what you see is what you get

I'd go for the following, assuming test.txt is the input and out.txt is the output:

with open('test.txt', 'r') as f:
     o = f.read()
with open('out.txt', 'a') as f:
     f.write('\n'.join(o.split()))
line = 'this is a text file'
line = line.replace(' ', '\n')
print(line)

output:

this
is
a
text
file

Use method above for open and write your file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM