我需要分析一些JSON文件。我使用iPython(Python 3.5.2 | IPython 5.0.0),将文件读入字典并将每个字典附加到列表中。在
我的主要瓶颈是读取文件。有些文件比较小,读起来很快,但是较大的文件会减慢我的速度。在
以下是一些示例代码(抱歉,我无法提供实际的数据文件):import json
import glob
def read_json_files(path_to_file):
with open(path_to_file) as p:
data = json.load(p)
p.close()
return data
def giant_list(json_files):
data_list = []
for f in json_files:
data_list.append(read_json_files(f))
return data_list
support_files = glob.glob('/Users/path/to/support_tickets_*.json')
small_file_test = giant_list(support_files)
event_files = glob.glob('/Users/path/to/google_analytics_data_*.json')
large_file_test = giant_list(event_files)
支持票的大小非常小——我见过的最大的是6KB。所以,这段代码运行得相当快:
^{pr2}$
但是更大的文件肯定会减慢我的速度…这些事件文件每个可以达到~2.5MB:In [7]: len(event_files) # there will be a lot more of these soon :-/
Out[7]: 397
In [8]: %timeit giant_list(event_files)
1 loop, best of 3: 14.2 s per loop
我研究过如何加快这个过程,并遇到了this post,然而,当使用UltraJSON时,时间稍微差一点:In [3]: %timeit giant_list(traffic_files)
1 loop, best of 3: 16.3 s per loop
SimpleJSON没有做得更好:In [4]: %timeit giant_list(traffic_files)
1 loop, best of 3: 16.3 s per loop
任何关于如何优化这段代码并更有效地将大量JSON文件读入Python的提示,我们将不胜感激。在
最后,this post是我发现的最接近我问题的地方,但是它处理的是一个巨大的JSON文件,而不是很多更小的文件。在