gpt4 book ai didi

python - 如何使用python快速读取25k小txt文件内容

转载 作者:太空宇宙 更新时间:2023-11-03 19:35:18 24 4
gpt4 key购买 nike

我在操作系统中下载了许多html存储,现在获取它们的内容,并提取我需要持久化到mysql的数据,我使用的是传统的逐一加载文件,效率不高,花费了将近8分钟。

欢迎任何建议

g_fields=[
'name',
'price',
'productid',
'site',
'link',
'smallImage',
'bigImage',
'description',
'createdOn',
'modifiedOn',
'size',
'weight',
'wrap',
'material',
'packagingCount',
'stock',
'location',
'popularity',
'inStock',
'categories',
] @cost_time
def batch_xml2csv():
"批量将xml导入到一个csv文件中"
delete(g_xml2csv_file)
f=open(g_xml2csv_file,"a")
import os.path
import mmap
for file in glob.glob(g_filter):
print "读入%s"%file
ff=open(file,"r+")
size=os.path.getsize(file)
data=mmap.mmap(ff.fileno(),size)
s=pq(data.read(size))
data.close()
ff.close()
#s=pq(open(file,"r").read())
line=[]
for field in g_fields:
r=s("field[@name='%s']"%field).text()
if r is None:
line.append("\N")
else:
line.append('"%s"'%r.replace('"','\"'))
f.write(",".join(line)+"\n")
f.close()
print "done!"

我尝试过mmap,似乎效果不好

最佳答案

如果磁盘上有 25,000 个文本文件,“你就错了”。根据您在磁盘上存储它们的方式,缓慢可能实际上是在磁盘上查找文件。

如果您有 25,0000 个任何东西,如果您将其放入具有智能索引的数据库中,速度会更快 - 即使您将索引字段设置为文件名,它也会更快快一点。

如果您有多个深度下降 N 层的目录,数据库仍然会更快。

关于python - 如何使用python快速读取25k小txt文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3878918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com