I am learning about reading/writing strings, lists, etc to txt/dat files. I wanted to add a comment in my code so I can refer back to what the access keys are. So this is what I did.
# Mode Description
# rb Read from a binary file. If the file doesn’t exist, Python will complain with an error.
# wb Write to a binary file. If the file exists, its contents are overwritten. If the file doesn’t exist,
# it’s created.
# ab Append a binary file. If the file exists, new data is appended to it. If the file doesn’t exist, it’s
# created.
# rb+ Read from and write to a binary file. If the file doesn’t exist, Python will complain with an
# error.
# wb+ Write to and read from a binary file. If the file exists, its contents are overwritten. If the file
# doesn’t exist, it’s created.
# ab+ Append and read from a binary file.
And after I have:
import pickle, shelve
print("Pickling lists.")
variety = ["sweet", "hot", "dill"]
shape = ["whole", "spear", "chip"]
brand = ["Claussen", "Heinz", "Vlassic"]
f = open("pickles1.dat", "wb")
pickle.dump(variety, f)
pickle.dump(shape, f)
pickle.dump(brand, f)
f.close()
print("\nUnpickling lists.")
f = open("pickles1.dat", "rb")
variety = pickle.load(f)
shape = pickle.load(f)
brand = pickle.load(f)
print(variety)
print(shape)
print(brand)
f.close()
When I run it I get the following error:
SyntaxError: Non-UTF-8 code starting with '\x92' in file PickleIt.py on line 10, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
I checked out the link, but I really don't understand it, I haven't seen this before.
Oh and apologies line 10 is # rb
Replace all the ’
by '
.
It's complaining because you didn't add the encoding type to the beginning of the file. The default encoding is utf-8
, in which those characters are not allowed.
Instead of replacing, you can add this line to the beginning (before the comments):
# coding: iso-8859-1
(Or another encoding in which those characters are present, like latin-1
for example.)
This line sets the encoding for the file and allows the use of special characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With