语境下打开多个文件:每个星期,我收到一个html文件的形式实验室结果的列表。每周大约有3000个结果,每组结果都有两到四个表格与之相关联。对于每个结果/试验,我只关心存储在这些表格之一中的一些标准信息。该表格可以唯一标识,因为第一个单元格的第一列始终具有“实验室结果”文本。BeautifulSoup的MemoryError当目录
问题:下面的代码在我每次执行每个文件时效果很好。也就是说,我没有对目录做一个for循环,而是将get_data = open()指向一个特定的文件。但是,我想抓取过去几年的数据,而不是单独执行每个文件。因此,我使用glob模块和一个for循环遍历目录中的所有文件。我遇到的问题是当我到达目录中的第三个文件时,我得到一个MemoryError。
问题:有没有办法清除/重置每个文件之间的内存?这样,我可以遍历目录中的所有文件,而不是分别粘贴每个文件名。正如你在下面的代码中看到的那样,我试图用del清除变量,但那不起作用。
谢谢。
from bs4 import BeautifulSoup
import glob
import gc
for FileName in glob.glob("\\Research Results\\*"):
get_data = open(FileName,'r').read()
soup = BeautifulSoup(get_data)
VerifyTable = "Clinical Results"
tables = soup.findAll('table')
for table in tables:
First_Row_First_Column = table.findAll('tr')[0].findAll('td')[0].text
if VerifyTable == First_Row_First_Column.strip():
v1 = table.findAll('tr')[1].findAll('td')[0].text
v2 = table.findAll('tr')[1].findAll('td')[1].text
complete_row = v1.strip() + ";" + v2.strip()
print (complete_row)
with open("Results_File.txt","a") as out_file:
out_string = ""
out_string += complete_row
out_string += "\n"
out_file.write(out_string)
out_file.close()
del get_data
del soup
del tables
gc.collect()
print ("done")
您是否尝试过做'get_data.close()'而不是'del'? – Anzel
@Anzel我试过了,但在运行之前得到以下错误:AttributeError:'str'对象没有'close'属性。我相信,因为它是get_data = open(FileName,'r').read(),.read()打开它,然后在读取它后关闭它。 – JohnR4785
对不起@ JohnR4785,它应该是'F =开放(...)','GET_DATA = f.read()','然后f.close()'... – Anzel