将文本文件保存在for循环中

时间:2018-07-19 16:06:25

标签: python

我试图遍历文件,将句子分成几行,然后导出该数据。

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

不幸的是,看起来循环仅经历了几行并保存了它们。因此,整个文件不会循环浏览并保存。我如何解决该问题有帮助吗?

3 个答案:

答案 0 :(得分:2)

这是我希望这是您想要实现的代码,

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

答案 1 :(得分:1)

每次使用from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC 选项重新打开文件时,基本上就删除了文件内容。

尝试像这样修改代码:

'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) 打开一个新文件,该文件会打开一个文件以进行追加,但是根据经验,请不要在循环中打开/关闭文件。

答案 2 :(得分:1)

open(filename, 'w')将在每次启动时覆盖文件。我的猜测是,当前正在发生的事情是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)

这样,您无需打开多次并每次覆盖它,只需打开一次并连续写入即可。