【问题标题】:python 2.7 cPickle append List [duplicate]python 2.7 cPickle追加列表[重复]
【发布时间】:2016-04-26 15:51:37
【问题描述】:

我正在尝试使用 python 2.7 中的 cPickle 写入附加到列表,但它没有附加。

代码:

import cPickle
import numpy
a = numpy.array([[1, 2],[3, 4]]);
output = open("1.pkl",'wb');
cPickle.dump(a,output);
a = numpy.array([[4, 5],[6, 7]]);
output = open("1.pkl",'ab');
cPickle.dump(a,output);
print(cPickle.load(open("1.pkl",'rb')));

输出:

[[1 2]
[3 4]]

我之前使用这种方法将数组追加到文本文件中

代码:

a = numpy.array([[1, 2],[3, 4]]);
text_file = open("1.txt", "w");
numpy.savetxt(text_file, a);
text_file.close();
a = numpy.array([[4, 5],[6, 7]]);
text_file = open("1.txt", "a");
numpy.savetxt(text_file, a);
text_file.close();

text_file = open("1.txt", "r");
print(text_file.read());

输出:

1.000000000000000000e+00 2.000000000000000000e+00
3.000000000000000000e+00 4.000000000000000000e+00
4.000000000000000000e+00 5.000000000000000000e+00
6.000000000000000000e+00 7.000000000000000000e+00

我正在使用它来编写我为 Power Systems 设置的 python 模拟的数据。输出数据很大,大约 7GB。编写过程大大减慢了模拟速度。我读到 cPickle 可以使写作过程更快。

如何在不读取整个数据的情况下追加到 cPickle 输出文件?

或者有没有比 cPickle 更好的替代品来加快写作速度?

【问题讨论】:

    标签: python-2.7 pickle


    【解决方案1】:

    我不相信你可以只附加到一个泡菜,或者以某种有意义的方式。

    如果您只是获取对象的当前序列化版本并在文件末尾添加另一个序列化对象,它不会只是神奇地将第二个对象附加到原始列表中。

    您需要读入原始对象,在 Python 中附加到它,然后将其转储回去。

    import cPickle as pickle
    import numpy as np
    
    filename = '1.pkl'
    
    a = np.array([[1, 2],[3, 4]])
    b = np.array([[4, 5],[6, 7]])
    
    # dump `a`
    with open(filename,'wb') as output_file:
        pickle.dump(a, output, -1)
    
    # load `a` and append `b` to it
    with open(filename, 'rb') as output_file:
        old_data = pickle.load(output_file)
        new_data = np.vstack([old_data,a])
    
    # dump `new_data`
    with open(filename, 'wb') as output_file:
        pickle.dump(new_data, output_file, -1)
    
    # test
    with open(filename, 'rb') as output_file:
        print(pickle.load(output_file))
    

    第二次阅读您的问题后,您声明您不想再次阅读整个数据。我想这并不能回答你的问题,是吗?

    【讨论】:

      猜你喜欢
      • 2019-04-06
      • 2020-08-08
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      • 2015-09-14
      相关资源
      最近更新 更多