1

可能重复:
builtins.TypeError:必须是 str,而不是字节

我编写了一个程序来将字典写入文件,在 Python 2.7 中它运行良好,但现在在 Python 3 中我收到TypeError: 'str' does not support the buffer interfaceTypeError: must be str, not bytes

代码更新

输入:目录路径、文件名(!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
4

1 回答 1

2

该文件应该以二进制打开

mfile = open(mfile,'rb')

mfile = open(self.add_slash(path)+fname, 'wb+')
于 2012-11-13T12:47:27.373 回答