簡體   English   中英

如何讀取文本文件並將其逐字寫入python中的另一個文件?

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

我有這樣的文本文件:

this is a text file.

我想將它保存到另一個文件中,如下所示:

this
is
a
text
file

每個單詞都進入了新的界限。 我也有這個非常簡單的代碼:

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)

但是在打印之后,所有的單詞都會寫在一起。 你能幫我個忙嗎? (只是一點暗示我應該怎么做)

當你這樣做時:

for word in line.split():

實際上你正在遍歷這個列表:

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

因為你split了空格。 然后當你把它寫回"test1.txt","a" ,你正在編寫那個列表中的所有內容而沒有任何分隔符或空格,所以這是你的輸出:

thisisatextfile.

現在,如果你想要每行上的每個單詞,只需要寫下與"\\n"連接的每個單詞,(新行字符)。

我對您的代碼進行了一些更改,應該如下所示:

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

讓我們仔細看看最重要的一行: f1.write('\\n'.join(line.split()))

  • str.split()會將字符串拆分為空白字符列表。 (標簽,空格,換行符)。 因此'word1 word2\\nword3\\tword4'.split()將是['word1', 'word2', 'word3', 'word4']

  • str.join(<iterable>)將迭代與給定的字符串連接在一起。 '\\n'.join(['word1', 'word2', 'word3', 'word4'])'word1\\nword2\\nword3\\nword4'

這個簡單的腳本可以解決您的問題:

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

您應該只打開一次輸出文件。

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

但如果您想堅持使用您的解決方案,只需在word后添加+ '\\n' 這將在您添加到文件的單詞后創建換行符。

write不寫任何你不寫的東西,所以你必須告訴它明確地寫一個新行"\\n" 或者,您可以使用自動放置新行的打印功能,以獲得如下所需的結果:

print(word,file=f1)

在python 3中,在python 2中是

print >>f1, word

在你的情況下將是

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)

那樣你所看到的就是你得到的

我會選擇以下內容,假設test.txt是輸入,out.txt是輸出:

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)

輸出:

this
is
a
text
file

使用上面的方法打開並寫入您的文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM