gpt4 book ai didi

Python - 尝试添加评论时出错

转载 作者:太空宇宙 更新时间:2023-11-03 12:49:00 25 4
gpt4 key购买 nike

我正在学习如何将字符串、列表等读/写到 txt/dat 文件。我想在我的代码中添加注释,以便我可以回顾访问 key 是什么。所以这就是我所做的。

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

当我运行它时,出现以下错误:

语法错误:第 10 行文件 PickleIt.py 中以 '\x92' 开头的非 UTF-8 代码,但未声明编码;见http://python.org/dev/peps/pep-0263/详情

我查看了链接,但我真的不明白,我以前没见过。


抱歉,第 10 行是 # rb

最佳答案

'替换所有的'。它在提示,因为您没有将编码类型添加到文件的开头。默认编码为 utf-8,其中不允许使用这些字符。

您可以将此行添加到开头(评论之前),而不是替换:

#编码:iso-8859-1

(或存在这些字符的另一种编码,例如 latin-1。)

此行设置文件的编码并允许使用特殊字符。

关于Python - 尝试添加评论时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17986978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com