2012-11-13 45 views
1

Possible Duplicate:
builtins.TypeError: must be str, not bytes的EOFError Python的2.7到3遷移

我寫了一個程序寫一個字典到文件,並在Python 2.7它工作得很好,但現在在Python 3我收到TypeError: 'str' does not support the buffer interfaceTypeError: must be str, not bytes

CODE修訂

輸入:路徑目錄,文件名(!hamers.txt例如)和新的字典

輸出:無

影響:生成與詞典的新文件。檢查文件是否存在,然後合併兩個字典(現有的和新的)。

def generate_file_from_dict(self, path, fname, my_new_dict):     
        mfile = self.add_slash(path)+fname 
      if os.path.exists(mfile): 
        mfile = open(mfile, 'rb') 
        my_existing_dict = pickle.load(mfile) 
        my_new_dict = dict(my_existing_dict.items() + my_new_dict.items()) 
        mfile.close() 
      mfile = open(self.add_slash(path)+fname, 'wb+') 
      pickle.dump(my_new_dict, mfile) 
      mfile.close() 

現在它

my_existing_dict = pickle.load(mfile) 
EOFError 
+0

打開我總是被這種問題的困惑,不錯誤告訴你究竟是什麼問題是?它說「」必須是一個str,而不是「」。還有什麼可以解釋,但意思是說,當你要傳遞'str'時,你正在嘗試傳遞'bytes'。 – SilentGhost

+0

嗯...也許我問,因爲在Python 2.7它工作正常!? – JohnDow

+0

可能你應該閱讀文檔? – SilentGhost

回答

2

文件應以二進制

mfile = open(mfile,'rb') 

mfile = open(self.add_slash(path)+fname, 'wb+') 
+0

'my_existing_dict = pickle.load(mfile) TypeError:'str'不支持緩衝區接口' – JohnDow

+1

@ VladislavIl'ushin:當使用pickle時,所有'open'調用應該使用'b'模式。 **所有通話。 – SilentGhost

+0

好吧,編輯它,但現在'my_existing_dict = pickle.load(mfile) EOFError',其中mfile是'mfile = open(mfile,'wb +')' – JohnDow