簡體   English   中英

Python在磁盤上的文件中存儲二進制數據

[英]Python Storing a Binary Data in File on disk

想知道將二進制數據存儲在磁盤上的文件中的最佳選擇是什么。 如果它將是內置的Python模塊,那就太好了,因為我想保留所有庫存。 可以隨機訪問書面數據,但這不是必須的。 對於此實現,我寧願追求簡單性和速度。 我正在尋找的是:現在保存-以后再獲取。 提前致謝!

編輯:

發現了一個問題,為什么cPickle出錯了。 在其中一個類中,我聲明了self.os = os,似乎self.os不是cPickle喜歡的東西……稍后,我發現cPickle不接受以下給定的PyQT對象(PyQT類實例):類的屬性(以防萬一您轉載some_class實例的列表)。

下面的示例if run復制相同的錯誤:

import cPickle
import os

class MyClass(object):
    """docstring for MyClass"""
    def __init__(self, arg):
        super(MyClass, self).__init__()
        self.arg = arg
        self.os=os         

data=MyClass("Hello World")    

file_name='dampData.data'

out_file = open(file_name, 'wb')
cPickle.dump(data, out_file)
out_file.close()

我會推薦cPickle-它也是內置的,並且比pickle快得多(在大多數情況下)。

例:

import cPickle

out_file = open(file_name, 'w')
cPickle.dump(data, out_file)
out_file.close()

in_file = open(file_name, 'r')
data = cPickle.load(in_file)
in_file .close()

泡菜的官方文檔中:

泡菜模塊具有稱為cPickle模塊的優化表弟。 顧名思義,cPickle用C編寫,因此它的速度可以比pickle快1000倍。

看看泡菜貨架模塊!

您可以使用普通的python函數讀取/寫入二進制文件。 如果在Windows上,請在模式中添加“ b”:

f = open('workfile', 'wb') # opens a file for writing in binary mode

如果您使用的是python 3,則可能需要對字符串編碼做更多的工作。

讀寫文件:

http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

您可能還希望序列化數據,以便更輕松地使用它

http://docs.python.org/2/library/pickle.html

它是內置的。

f = open("somefile.zip", "rb")
g = open("thecopy.zip", "wb")

while True:
    buf = f.read(1024)
    if len(buf) == 0:
         break
    g.write(buf)

f.close()
g.close()

http://openbookproject.net/thinkcs/python/english3e/files.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM