python读取大量文件并将信息写入单个txt文件
我有一个包含30911个html文件的文件夹。我想将所有文件名和一些所需信息(使用beautifulsoup)写入一个txt文件,每个文件名将占用一行python读取大量文件并将信息写入单个txt文件,python,file,io,Python,File,Io,我有一个包含30911个html文件的文件夹。我想将所有文件名和一些所需信息(使用beautifulsoup)写入一个txt文件,每个文件名将占用一行 file1.html file2.html file3.html .. file30911.html 我遇到的问题是,有时它会出错,因为文件的格式不一致 所以,我想在它停止时仍然保留完整的信息。然后,当我重新运行代码时,它将从停止的地方开始,并将留下的信息添加到文件中。 有人能帮我把这个目的添加到我的代码中吗 我的代码: import re,
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()
我会将现有的“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
这些文件是不变的吗?或者是否有可能修改、添加或删除文件?当遇到不一致时会发生什么情况?例外?你能抓住它继续下一个文件吗?还有多少不一致之处?仅仅是一些或很多,你能不能用一种不受这些影响的方式来编写你的bs代码?很难提出解决方案,因为您已经从较高的层次解释了您的问题,但没有提供任何细节。@AustinHastings文件未更改。我将index.txt输出到另一个文件夹,虽然例外块是catch no find the required content atm@PaulRooney,但我不确定有多少个,因为我没有检查所有30911文件……还是最好将已完成的html文件移到其他文件夹,以便下次我重新运行代码时,它将只执行其余文件