1

Possible Duplicate:
builtins.TypeError: must be str, not bytes

I wrote a program to write a dict to file and in Python 2.7 it works well, but now in Python 3 I receive TypeError: 'str' does not support the buffer interface and TypeError: must be str, not bytes

CODE UPDATED

Inputs: path to dir, file name (!hamers.txt for example) and new dictionary

Outputs: none

Effects: Generate new file with dictionary. Check if file exists and then merge two dictionaries (existing and new).

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()

Now its

my_existing_dict = pickle.load(mfile)
EOFError
Community
  • 1
  • 1
JohnDow
  • 1,242
  • 4
  • 22
  • 40
  • I'm always puzzled by this sort of question, doesn't the error tell you what exactly the problem is? It says `"must be a str, not bytes"`. How else could this be interpreted but to mean, that you're trying to pass `bytes`, when you should pass `str`. – SilentGhost Nov 13 '12 at 12:48
  • Hmmm... maybe I ask because on Python 2.7 it works fine!? – JohnDow Nov 13 '12 at 12:50
  • May be you should read docs? – SilentGhost Nov 13 '12 at 12:53
  • @VladislavIl'ushin: When switching a major version of anything, you should expect that not everything works. This might help you: http://docs.python.org/3/howto/pyporting.html – lqc Nov 13 '12 at 12:57

1 Answers1

2

The file should opened in binary

mfile = open(mfile,'rb')

mfile = open(self.add_slash(path)+fname, 'wb+')
PearsonArtPhoto
  • 38,970
  • 17
  • 111
  • 142
  • `my_existing_dict = pickle.load(mfile) TypeError: 'str' does not support the buffer interface` – JohnDow Nov 13 '12 at 12:49
  • 1
    @VladislavIl'ushin: all `open` calls should use `b` mode, when using pickle. **all** calls. – SilentGhost Nov 13 '12 at 12:52
  • OK, a edit it, but now `my_existing_dict = pickle.load(mfile) EOFError`, where mfile is `mfile = open(mfile, 'wb+')` – JohnDow Nov 13 '12 at 12:56
  • @VladislavIl'ushin: read the answer. People are actually trying to help you. Is this what Pearsonartphoto suggested you do? – SilentGhost Nov 13 '12 at 13:00
  • Look at my updated code, look at answer, at my code, at answer. Of course I do `'wb+'` thing. – JohnDow Nov 13 '12 at 13:02
  • @VladislavIl'ushin: I have and that's why I'm telling you to read the answer again. Why on earth you're _`'wb+' thing_ I have no idea. – SilentGhost Nov 13 '12 at 13:04