我正在学习如何读取/写入txt / dat文件的字符串,列表等。我想在我的代码中添加注释,以便我可以参考访问键的内容。所以这就是我所做的。
# 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.
我有:
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()
当我运行它时,我收到以下错误:
SyntaxError:第10行文件PickleIt.py中以'\ x92'开头的非UTF-8代码,但未声明编码;有关详细信息,请参阅http://python.org/dev/peps/pep-0263/
我检查了链接,但我真的不明白,我以前没见过。
哦,道歉第10行是# rb
答案 0 :(得分:7)
将所有’
替换为'
。
它抱怨,因为您没有将编码类型添加到文件的开头。默认编码为utf-8
,其中不允许使用这些字符。
您可以将此行添加到开头(注释之前),而不是替换:
# coding: iso-8859-1
(或其他编码,其中存在这些字符,例如latin-1
。)
此行设置文件的编码并允许使用特殊字符。
答案 1 :(得分:2)
将智能引号’
替换为评论中的常规引用'
。
答案 2 :(得分:0)
这个角色似乎是问题'