【问题标题】:Python - Error when trying to add commentsPython - 尝试添加评论时出错
【发布时间】:2013-08-01 22:59:56
【问题描述】:

我正在学习如何在 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

【问题讨论】:

  • 删除评论中的apostrophes,然后重试
  • 哇,解决了,谢谢。我删除并替换了它们。这是否意味着 python 或 ide 无法识别我复制过来的 '?
  • 不是utf-8 支持的字符,我认为是ascii 什么的

标签: python python-3.x syntax-error


【解决方案1】:

将您的 cmets 中的智能引号 替换为常规引号 '

【讨论】:

    【解决方案2】:

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

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

    # coding: iso-8859-1

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

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

    【讨论】:

    • 谢谢,这很有帮助。
    • @mccdlibby 很高兴我能帮上忙 :)
    【解决方案3】:

    这个字符似乎是问题'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-20
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-13
      相关资源
      最近更新 更多