【问题标题】:ascii codec can't decodeascii编解码器无法解码
【发布时间】:2016-10-03 03:34:01
【问题描述】:

我在尝试打开目录中的所有 .txt 文件时遇到错误,当目录中只有 1 个 txt 文件时,我的代码可以正常工作,否则会弹出此消息:

Traceback (most recent call last):
  File "/Users/Name/Desktop/TCSS 142/Project 2/project2.py", line 17, in <module>
for line in file:
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/encodings/ascii.py", line 26, in decode
   return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 3: ordinal not in range(128)

这是我的代码:

import glob

# Returns a list of all filenames ending in .txt
# precondition: none
# postcondition: a list of all filenames in the current directory
#                with a .txt extension
def getFilesInDir():
    filenames = glob.glob('./*.txt')
    for i in range(len(filenames)):
        filenames[i] = filenames[i][2:]
    return filenames

files = getFilesInDir()

for el in files:
    file = open(el, 'r')
    for line in file:
        print(line)
    file.close()

【问题讨论】:

  • 尝试在文件顶部添加# -*- coding: utf-8 -*-这个
  • 你能发布完整的回溯吗?
  • 0x92 是(单个,正确的)智能引号,它可能在您的一个文件中,并且可能隐藏为一个简单的 ascii 撇号 '
  • @Evert 你能解释一下什么是完整的回溯吗?
  • 你不也用codecs吗?因为您的错误是关于 codecs.ascii_decode 并且您没有在代码中使用它。

标签: list python-3.x encoding ascii utf


【解决方案1】:

好的,@Evert 的评论解决了我的问题,当我打开文件时,我的 open 语句如下所示:

file = open(el, 'r', encoding = 'cp1252')

【讨论】:

    【解决方案2】:

    您的默认编码(用于读取文件)似乎是 ASCII;它无法读取的字符似乎是 (Windows) 智能引号(“卷曲”撇号 ')。

    为了能够读取文件,您需要指定其编码。我不认为0x92 是一个有效的UTF 代码点(但我可能弄错了);因为这是 Windows 智能报价,请尝试 Windows latin alphabet encoding cp1252

    file = open(el, 'r', encoding = 'cp1252')
    

    【讨论】:

      猜你喜欢
      • 2011-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-01
      • 2015-11-06
      • 2013-08-17
      • 2016-10-04
      • 2011-06-29
      相关资源
      最近更新 更多