繁体   English   中英

存储和检索文件中的列表

[英]storing and retrieving lists from files

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

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中有效地存储和检索文件中的大列表或列表列表?

您可以将列表序列化为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 )。 这也适用于自定义对象。

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

它会更快:

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()))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM