Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Error when trying to add comments

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

like image 356
mccdlibby Avatar asked Dec 26 '22 23:12

mccdlibby


1 Answers

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.

like image 194
koplersky Avatar answered Jan 10 '23 16:01

koplersky