2010-02-14 18 views
1

你能幫助我做這個例子嗎?使用cPickle的問題

我想加載一個序列化的字典,如果它存在,修改它並轉儲它。我認爲我用於打開文件的模式存在問題,但我不知道正確的方法。

import os 
import cPickle as pickle 

if os.path.isfile('file.txt'): 
    cache_file = open('file.txt', 'rwb') 
    cache = pickle.load(cache_file) 
else: 
    cache_file = open('file.txt', 'wb') 
    cache = dict.fromkeys([1,2,3]) 

# modifications of cache 

pickle.dump(cache, cache_file) 
cache_file.close()  

運行它兩次來查看錯誤:

Traceback (most recent call last): 
    File "example.py", line 11, in <module> 
    pickle.dump(cache, cache_file) 
IOError: [Errno 9] Bad file descriptor 

回答

4

對於每個負載,您需要打開(使用mode ='rb'),加載並關閉文件句柄。
對於每個轉儲,您需要打開(使用mode ='wb'),轉儲並關閉文件句柄。

5

'rwb'不是open()正確的文件打開方式。嘗試'r+b'

從文件讀取後,光標位於文件末尾,因此pickle.dump(cache, cache_file)將附加到文件(可能不是您想要的)。在pickle.load(cache_file)之後嘗試cache_file.seek(0)

1

您已打開文件進行讀取和寫入 - 即隨機訪問。最初讀取文件時,將文件索引位置保留在文件末尾,因此,稍後將數據寫回時,您將追加到同一文件。

您應該以讀取模式打開文件,讀取數據,關閉它,然後以寫入模式重新打開。