存储和检索文件

时间:2016-08-22 06:59:43

标签: python list

我有一个非常大的列表列表。我的一个程序就是这样做的:

power_time_array = [[1,2,3],[1,2,3]] # In a short form

with open (file_name,'w') as out:
        out.write (str(power_time_array))

现在另一个独立脚本需要回读这个列表列表。

我该怎么做?

我尝试过:

with open (file_name,'r') as app_trc_file :
    power_trace_of_application.append (app_trc_file.read())

注意:power_trace_application是列表列表的列表。

这将它存储为一个列表,其中一个元素为一个巨大的字符串。

如何在python中有效地存储和检索文件中的大列表或列表列表?

3 个答案:

答案 0 :(得分:3)

您可以将列表序列化为json并将其反序列化。这在表示中确实没有任何改变,你的列表已经是有效的json:

import json 


power_time_array = [[1,2,3],[1,2,3]] # In a short form

with open (file_name,'w') as out:
    json.dump(power_time_array, out)

然后再读回来:

with open (file_name,'r') as app_trc_file :
    power_trace_of_application = json.load(app_trc_file)    

对于速度,您可以使用带有C后端的json库(如 ujson )。这也适用于自定义对象。

答案 1 :(得分:3)

使用Json库有效地读取和写入结构化信息(以JSON的形式)到文本文件。

  • 要在文件上写入数据,请使用json.dump()
  • 要从文件中检索json数据,请使用json.load()

答案 2 :(得分:0)

会更快:

from ast import literal_eval


power_time_array = [[1,2,3],[1,2,3]]


with open(file_name, 'w') as out:
    out.write(repr(power_time_array))


with open(file_name,'r') as app_trc_file:
    power_trace_of_application.append(literal_eval(app_trc_file.read()))