python - 为什么我在这里收到 UnicodeDecodeError ?

标签 python python-3.x

我正在尝试编写一个 python 脚本来查找 USB 闪存驱动器中的重复文件。

我遵循的过程是创建文件名列表,对每个文件进行哈希处理,然后创建一个逆字典。然而,在这个过程中的某个地方,我收到了 UnicodeDecodeError。有人可以帮助我了解发生了什么事吗?

from os import listdir
from os.path import isfile, join
from collections import defaultdict
import hashlib

my_path = r"F:/"

files_in_dir = [ file for file in listdir(my_path) if isfile(join(my_path, file)) ]
file_hashes = dict()

for file in files_in_dir:
    file_hashes[file] = hashlib.md5(open(join(my_path, file), 'r').read()).digest()

inverse_dict = defaultdict(list)

for file, file_hash in file_hashes.iteritems():
    inverse_dict[file_hash].append(file)

inverse_dict.items()

我遇到的错误是:

Traceback (most recent call last):
  File "C:\Users\Fotis\Desktop\check_dup.py", line 12, in <module>
    file_hashes[file] = hashlib.md5(open(join(my_path, file), 'r').read()).digest()
  File "C:\Python33\lib\encodings\cp1253.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0xff in position 2227: character maps to <undefined>

最佳答案

您正在尝试读取未使用默认平台编码 (cp1253) 进行编码的文件。通过以文本模式 (r) 打开文件,Python 3 将尝试将文件内容解码为 un​​icode。您没有指定编码,因此使用平台首选编码。

改为以二进制模式打开文件,使用 rb 作为模式。由于您仅计算 MD5 哈希值(需要字节的函数),因此您无论如何都不应该使用文本模式。

关于python - 为什么我在这里收到 UnicodeDecodeError ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13689166/

相关文章:

Python (3.7) CSV 按字段值排序/求和

python - 正在分析 pyspark udf 打印行

python-3.x - 在 Python 中按位修改整数

python - 如何通过统计分析创建移动平均函数..?

python - Python 中的击键事件

python - 如何检查模块是否已导入

python - 我怎样才能让我的代码生成相似但仍然不同的结果而不需要全部输入?

python - Python 中包的供应商命名空间

python - python中的屏幕截图

Python3 Http Web 服务器 : virtual hosts