2017-05-30 10 views
0

私は30911 htmlファイルを含むフォルダを持っています。私はすべてのファイル名といくつかの望ましい情報(beautifulsoupを使って)をtxtファイルに書きたいと思います。各ファイル名は1行になります。pythonがたくさんのファイルを読み込んで単一のtxtに情報を書き込む

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ファイルは変更されていません。 –

答えて

0

私は既存の「/output1/index.txt C」を読んでいました。

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 
関連する問題