2015-05-22 46 views
-1

我有以下代碼:蟒蛇鹹菜轉儲tar文件

import cPickle as pickle 
... 
pickle.dump(wave, open(a_file, 'wb'), protocol=2) 

工作正常。我想,所以我試圖做

pickle.dump(wave, tarfile.open(a_file, 'w:bz2'), protocol=2) 

壓縮雖然使用BZ2文件,但我不斷收到此錯誤:

TypeError: argument must have 'write' attribute 

不鹹菜只是不能正確識別的tar文件?我將如何執行一個pickle轉儲到tarfile?

回答

0

問題是錯誤狀態。 Python的tarfiles根本沒有相同的文件接口;你不能直接寫信給他們,而是通過TarInfo對象來操作它們。


你可以使用字符串泡菜形式:

tarinfo = TarInfo.frombuf(pickle.dumps(wave, protocol=2)) 

打開tar文件

out = tarfile.open(filename, mode=('tarfile_compression.tar.bz2', 'w:bz2')) 

然後用TarFile.addfile添加tarinfoout

+0

我想,這是錯誤的原因'TarInfo.frombuf''從512字節字節對象構造一個TarInfo對象.' – Winand