2017-05-30 109 views
0

我有一個包含30911 html文件的文件夾。我想將所有文件名和一些需要的信息(使用beautifulsoup)寫入一個txt文件,每個文件名將佔據一行。python讀取大量文件並將信息寫入單個文本文件

file1.html 
file2.html 
file3.html 
.. 
file30911.html 

我遇到的問題是,有時它有錯誤,因爲文件的格式不一致。

因此,我想在停止時仍保留完整的信息。然後,當我重新運行代碼時,它將從停止的任何地方開始,並將左側信息添加到文件中。 任何人都可以幫助將此目的添加到我的代碼?

我的代碼:

import re, os, bs4, glob 
path = 'C:/output/' #all the 30911 html files 
for filename in glob.glob(os.path.join(path, '*.html')): 
    #I will not post beautifulsoup's code to save space here. 
    try: 
     #some beautifulsoup code to find tags 
    except: 
     indexFile = open('C:/output1/' + 'index.txt', 'a+') 
     indexFile.write(os.path.basename(filename) + ', ' + title.get_text(strip=True) + 'no participants') 
    else: 
     indexFile = open('C:/output1/' + 'index.txt', 'a+') 
     indexFile.write(os.path.basename(filename) + ', ' + title.get_text(strip=True) + ', '+ parti_names) 
     indexFile.close() 
+0

這些文件不變嗎?或者有沒有機會修改,添加或刪除文件? –

+0

當你遇到不一致時會發生什麼?例外?你能抓住它並繼續下一個文件嗎?還有多少不一致?只是少數或很多,你不能以不受這些影響的方式編寫你的bs代碼嗎?提出解決方案非常困難,因爲您已經在高層解釋了您的問題,但沒有提供具體細節。 –

+0

@AustinHastings文件保持不變。我輸出index.txt到另一個文件夾,雖然 –

回答

0

我會讀取現有的「C:/output1/index.txt」文件到列表,並追加前行對證新的生產線。

existing_files = [] 

with open('C:/output1/index.txt') as infile: 
    for item in infile: 
     existing_files.append(item) 
    #do parsing here 
    #then check before you append to the file 
    if file_to_write not in existing_files: 
     #append the file 
相關問題