簡體   English   中英

將文本文件保存在for循環中

[英]Saving text file in a for loop

我正在嘗試遍歷文件,將句子剝離成單獨的行,然后導出該數據。

filename = '00000BF8_ar.txt'

with open(filename, mode="r") as outfile:   
    str_output = outfile.readlines()
    str_output = ''.join(str_output)
    sentenceSplit = filter(None, str_output.split("."))

    for s in sentenceSplit:
        print(s.strip() + ".")
        #output += s 



        myfile = open(filename, 'w')
        myfile.writelines(s)
        myfile.close()

不幸的是,看起來循環僅經歷了幾行並保存了它們。 因此,整個文件不會循環瀏覽並保存。 我如何解決該問題有任何幫助嗎?

這是我希望這是您想要實現的代碼,

filename = '00000BF8_ar.txt'

with open(filename, mode="r") as outfile:   
    str_output = outfile.readlines()
    str_output = ''.join(str_output)
    sentenceSplit = filter(None, str_output.split("."))
    l=[]

    for s in sentenceSplit:
        l.append(s.strip() + ".")
    myfile = open(filename, 'w')
    myfile.write('\n'.join(l))
    myfile.close()

每次使用'w'選項重新打開文件時,基本上都將擦除其內容。

嘗試像這樣修改代碼:

filename = '00000BF8_ar.txt'

with open(filename, "r") as infile:
    str_output = infile.readlines()

str_output = ''.join(str_output)
sentenceSplit = filter(None, str_output.split("."))

with open(filename, "w") as outfile:
    for s in sentenceSplit:
        print(s.strip() + ".")
        #output += s 
        s.writelines(s)

實現相同目的的另一種方法是使用open(filename_new, 'a')打開一個新文件open(filename_new, 'a')該文件會打開一個文件以進行追加,但是根據經驗,請盡量不要在循環內打開/關閉文件。

open(filename, 'w')每次啟動時都會覆蓋該文件。 我的猜測是,當前正在發生的事情是myFile中只顯示了sentenceSplit myfile的最后一個元素。

簡單的“解決方案”是使用append而不是write

open(filename, 'a')

它將僅在文件末尾開始寫入,而不會刪除其余部分。

然而,由於@ chepner的評論狀態,你為什么要重新打開該文件呢? 我建議將您的代碼更改為此:

with open(filename, mode="r") as outfile:   
    str_output = outfile.readlines()
    str_output = ''.join(str_output)
    sentenceSplit = filter(None, str_output.split("."))

with open(filename, mode='w') as myfile:
    for s in sentenceSplit:
        print(s.strip() + ".")
        myfile.writelines(s)

這樣,您不必打開多次並每次覆蓋它,只需打開一次並連續寫入即可。

暫無
暫無

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

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