Python 读取 txt 数据存 mangodb

2022-08-05 09:12:31 +08:00
 QGabriel
我现在的读取存方法太慢了,希望大佬能给点建议提升效率.

def file_name(url):
for root, dirs, files in os.walk(url):
for i in range(len(files)):
f = open('c:/test/txt/file/' + files[i][:files[i].index('.txt')] + '.txt')
next(f)
for j in f:
res = j.split(' ')
obj = {}
for k in res:
if len(res) > 2:
obj = {
"trade_date": res[0],
"time": res[1],
"open": float(res[2]) if res[2] else '',
"high": float(res[3]) if res[3] else '',
"low": float(res[4]) if res[4] else '',
"close": float(res[5]) if res[5] else '',
"vol": float(10)
}
if obj and obj['trade_date'] != '':
name = files[i][:files[i].index('.txt')]
origin = client['abc'][name]
origin.insert_one(obj)
# print()
print(i, files[i][:files[i].index('.txt')], 'end')

file_name('c:/test/txt/file/')



txt 文件:
B2210 豆二 2210 1 分钟线 前复权
日期 时间 开盘 最高 最低 收盘 成交量 持仓量 结算价
20211025 0901 3853 3853 3853 3853 0 0 0
1773 次点击
所在节点    Python
7 条回复
kaedeair
2022-08-05 09:19:09 +08:00
任务切块扔进程池
tairan2006
2022-08-05 09:27:03 +08:00
你不要一条一条插啊…批量写入
CaptainD
2022-08-05 09:53:16 +08:00
用 pandas 批量处理 txt ,然后批量构建 obj ,再插入,然后再分块多进程,这个思路是不是好点
vhysug01
2022-08-05 09:57:15 +08:00
这类型数据我存过,用的是 bcolz 存的,文件形式落盘
httplife
2022-08-05 10:00:47 +08:00
空白键换成 , 另存为 csv. 然后 import?
root000
2022-08-05 10:37:48 +08:00
https://www.mongodb.com/docs/database-tools/mongoimport/

可以试试官方的工具 但是需要转下文件格式 目前只支持 JSON, CSV, or TSV

目前在用这个来导
SenLief
2022-08-05 10:39:04 +08:00
把 txt 先整成 csv ,那就效率高了。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/870781

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX