-1

I kept the module pickle in my directory. Now, I want to store the variable i.e. Arpan in a created file called spdict.data So, when i enter the code as follows:

    import pickle
    Arpan = "My name is Arpan"
    fh = open("spdict.data","w")
    pickle.dump(Arpan,fh)
    fh.close()

I would expect the variable Arpan to get stored, but I get the following error.

Traceback (most recent call last): File "C:\Users\Home\AppData\Local\Programs\Python\Python36-32\IDLE scripts for bioinfo book\File handling\test1 reading fasta.py", line 173, in pickle.dump(Arpan,fh) TypeError: write() argument must be str, not bytes

Also, when I enter the program

import pickle
Arpan = {"One":1,"Two":2,"Three":3}
fh = open("spdict.data","w")
pickle.dump(Arpan,fh)
fh.close()

Then also, following error comes:

Traceback (most recent call last): File "C:\Users\Home\AppData\Local\Programs\Python\Python36-32\IDLE scripts for bioinfo book\File handling\test1 reading fasta.py", line 173, in pickle.dump(Arpan,fh) TypeError: write() argument must be str, not bytes

Please help.. My python version is 3.6.4

1 Answers1

1

When writing pickles, open your files for binary writing.

fh = open("spdict.data", "wb")
tzot
  • 92,761
  • 29
  • 141
  • 204
  • Now, when I try to retrieve it by the following code, fh = open("spdict.data") Arpan = pickle.load(fh) print(Arpan) fh.close() it gives a following error line 180, in Arpan = pickle.load(fh) TypeError: a bytes-like object is required, not 'str' – Dr. Arpan Mehta May 13 '18 at 09:54
  • Yes, I tried the first solution, it worked.. and then when I tried to retrieve the stored variable 'Arpan', I got stuck up with the above error.. Please excuse me for my ignorance. – Dr. Arpan Mehta May 13 '18 at 09:59
  • 1
    Ok, I tried retrieving in binary form.. and it worked..Thanks all. – Dr. Arpan Mehta May 13 '18 at 10:06