我有一个3.7gb的大json数据文件。IAM将JSON文件加载到数据帧并删除未使用的列,然后将其转换为CSV并加载到SQL。内存是40GB我的json文件结构
{"a":"Ho Chi Minh City, Vietnam","gender":"female","t":"841675194476","id":"100012998502085","n":"Lee Mến"}
{"t":"84945474479","id":"100012998505399","n":"Hoàng Giagia"}
{"t":"841679770421","id":"100012998505466","n":"Thoại Mỹ"}
我尝试加载数据,但是由于内存不足而失败
data_phone=[]
with open('data.json', 'r', encoding="UTF-8") as f:
numbers = ijson.items(f, 't',multiple_values=True)
for num in numbers :
data_phone.append(num)
显示错误
Out of memory
我尝试另一种方式
import json fb_data = {} i = 1
with open('output.csv', 'w') as csv_file:
with open("Vietnam_Facebook_Scrape.json", encoding="UTF-8") as json_file:
for line in json_file:
data = json.loads(line)
try:
csv_file.write('; '.join([str(i),"/",data["t"],data["fbid"]]))
except:
pass
然后,我从csv转换为sql,它仍然显示错误“ MemoryError:”
con = db.connect("fbproject.db")
cur = con.cursor()
with open('output.csv', 'r',encoding="UTF-8") as csv_file:
for item in csv_file:
cur.execute('insert into fbdata values (?)', (item,))
con.commit()
con.close()
谢谢阅读
您的建议是:
你的第二个例子的问题是,你仍然可以使用全局列表(data_phone
,data_name
),它随时间增长。
对于大型文件,这是您应该尝试的方法:
您无需将任何内容写入CSV。如果确实需要,您可以简单地逐行写入文件:
import json
with open('output.csv', 'w') as csv_file:
with open("Vietnam_Facebook_Scrape.json", encoding="UTF-8") as json_file:
for line in json_file:
data = json.loads(line)
csv_file.write(';'.join([data['id'], data['t']]))
这是一个可能对您有所帮助的问题(Python和SQLite:插入table),以便逐行写入数据库。
如果要改用CSV,请确保用于将CSV转换为SQL的程序不会读取整个文件,而是逐行或批量解析它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句