Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python处理包含数组的二进制文件_Python_List_File_Binary - Fatal编程技术网

使用python处理包含数组的二进制文件

使用python处理包含数组的二进制文件,python,list,file,binary,Python,List,File,Binary,我从两个大文件中读取并提取一些数字,将它们存储在两个列表中。 然后根据存储的列表制作直方图 读取所有文件以生成2个列表需要很长时间。我想,如果我将列表存储在一个文件中,我就可以重用它们,而无需再次读取所有文件 现在列表也很大,所以如果我以二进制文件的形式编写,它包含两个列表,如 [1,2,3,4,5,6,7..] [a,b,c,d,e,f..] 如何处理此二进制文件并在中读取这两个数组? 对于较小的列表,当我这样做时,我只需存储它,然后复制它,并将其粘贴到处理代码中,如下所示 x= [1,2,

我从两个大文件中读取并提取一些数字,将它们存储在两个列表中。 然后根据存储的列表制作直方图

读取所有文件以生成2个列表需要很长时间。我想,如果我将列表存储在一个文件中,我就可以重用它们,而无需再次读取所有文件

现在列表也很大,所以如果我以二进制文件的形式编写,它包含两个列表,如

[1,2,3,4,5,6,7..]
[a,b,c,d,e,f..]
如何处理此二进制文件并在中读取这两个数组? 对于较小的列表,当我这样做时,我只需存储它,然后复制它,并将其粘贴到处理代码中,如下所示

x= [1,2,3,4,5,6,7..]
y=[a,b,c,d,e,f..]
谢谢

试试看。 这会将您的列表保存到“out.dat”:

with open('out.dat', 'wb') as pkl_file: 
    pickle.dump([x,y], pkl_file, -1)
这将在以后加载它们:

with open('out.dat', 'rb') as pkl_file: 
    x,y = pickle.load(pkl_file)
因此,您可以在代码中输入如下内容:

if not os.path.exists('out.dat'):
    x, y = generate_x_y() #your time consuming method
    with open('out.dat', 'wb') as pkl_file: 
        pickle.dump([x,y], pkl_file, -1)
else:
    with open('out.dat', 'rb') as pkl_file: 
        x,y = pickle.load(pkl_file)
这是一个好办法。如果你想要便携性,你可以选择

另一个经常被忽视的选择是使用

import json

x = [1,2,3,4,5,6,7]
y = ['a','b','c','d','e','f']

with open('saved_data.json', 'w') as f:
    json.dump([x, y], f)    # or as a dict: json.dump(dict(x=x, y=y))

# To read it back...

with open('saved_data.json') as f:
    x, y = json.load(f)

>>> x
[1, 2, 3, 4, 5, 6, 7]
>>> y
[u'a', u'b', u'c', u'd', u'e', u'f']
>>> import shelve
>>> shelf = shelve.open('saved_data.shelf')
>>> shelf
{}
>>> shelf['x'] = x
>>> shelf['y'] = y
>>> shelf
{'y': ['a', 'b', 'c', 'd', 'e', 'f'], 'x': [1, 2, 3, 4, 5, 6, 7]}
>>> shelf.close()

>>> shelf = shelve.open('saved_data.shelf')    # reopen shelf
>>> shelf['x']
[1, 2, 3, 4, 5, 6, 7]
>>> shelf['y']
['a', 'b', 'c', 'd', 'e', 'f']