2012-12-03 4 views
1

나는 파이썬 스크립트를 만들어 USB 플래시 드라이브에서 중복 파일을 찾으려고합니다.왜 UnicodeDecodeError가 표시됩니까?

다음 과정은 각 파일을 해시 한 다음 역 사전을 만드는 파일 이름 목록을 만드는 것입니다. 그러나 어딘가에있는 과정에서 나는 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() 

오류 : 당신은 기본 플랫폼 인코딩 (cp1253)로 인코딩되지 않은 파일을 읽으려는

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> 
+0

@Martijn Pieters 그것은 python입니다. 3. 적절한 질문을 다시합니다. – NlightNFotis

답변

4

. 텍스트 모드 (r)로 파일을 열면 Python 3은 파일 내용을 유니 코드로 디코드하려고 시도합니다. 인코딩을 지정하지 않았으므로 플랫폼 기본 인코딩이 사용됩니다.

모드로 rb을 사용하여 이진 모드로 파일을 엽니 다. MD5 해시 (바이트를 예상하는 함수) 만 계산하기 때문에 어쨌든 텍스트 모드를 사용하지 않아야합니다.

+0

감사합니다. 나는 항상 당신을 의지 할 수있는 해결책이 있습니다! – NlightNFotis

관련 문제