2014-02-15 4 views
0

저는 비교적 Python 프로그래밍에 익숙하지 않습니다. Windows XP에서 Python 3.3.2를 사용하고 있습니다.Python의 UnicodeDecodeError 메시지

내 프로그램이 작동하고 갑자기 UnicodeDecodeError 오류 메시지가 나타납니다.

exec.py 파일은 다음과 같습니다 :

import re 
import os,shutil 
f=open("C:/Documents and Settings/hp/Desktop/my_python_files/AU20-10297-2_yield_69p4_11fails_2_10_14python/a1.txt","a") 
for r,d,fi in os.walk("C:/Documents and Settings/hp/Desktop/my_python_files/AU20-10297-2_yield_69p4_11fails_2_10_14python"): 
for files in fi: 
    if files.startswith("data"): 
     g=open(os.path.join(r,files)) 
     shutil.copyfileobj(g,f) 
     g.close() 
f.close() 

keywords = ['FAIL'] 
pattern = re.compile('|'.join(keywords)) 



inFile = open("a1.txt") 
outFile =open("failure_info", "w") 
keepCurrentSet = False 
for line in inFile: 
if line.startswith("         Test Results"): 
    keepCurrentSet = False 

if keepCurrentSet: 
    outFile.write(line) 

if line.startswith("Station ID "): 
    keepCurrentSet = True 

#if 'FAIL' in line in inFile: 
    # outFile.write(line) 

if pattern.search(line): 
    outFile.write(line) 

inFile.close() 
outFile.close() 

지금, a1.txt 처음에 데이터 파일에서 데이터를 수집하는 데 사용 빈 씨 텍스트 파일입니다.

Traceback (most recent call last): 
    File "C:\Documents and Settings\hp\Desktop\my_python_files\AU20-10297-2_yield_69p4_11fails_2_10_14python\exec.py", line 8, in <module> 
    shutil.copyfileobj(g,f) 
    File "C:\Python33\lib\shutil.py", line 68, in copyfileobj 
    buf = fsrc.read(length) 
    File "C:\Python33\lib\encodings\cp1252.py", line 23, in decode 
    return codecs.charmap_decode(input,self.errors,decoding_table)[0] 
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 754: character maps to <undefined> 

사람이 더 강력한 그래서 내가 코드를 해결하는 데 도움을 줄 수 있습니다 : 나는 다음과 같은 오류 메시지가 있어요?

답변

1

파일을 텍스트 모드로 열었습니다. 즉, 파이썬은 내용을 유니 코드로 디코딩하려고 시도합니다. 일반적으로 파일의 올바른 코덱을 지정해야합니다 (또는 Python이 플랫폼 기본값을 사용합니다). 여기서는 shutil.copyfileobj()으로 파일을 복사하고 디코딩 할 필요가 없습니다.

파일을 대신 이진 모드로 엽니 다.

f = open(..., 'ab') 
for r,d,fi in os.walk(...): 
    for files in fi: 
     if files.startswith("data"): 
      g = open(os.path.join(r, files), 'rb') 
      shutil.copyfileobj(g,f) 

파일 모드에 b이 추가되었습니다. 그들은 당신을 위해 폐쇄되도록

당신은 아마 자동으로 상황에 맞는 관리자로 파일 객체를 사용하려면 : 내 문제를 해결하기위한

with open(..., 'ab') as outfh: 
    for r,d,fi in os.walk(...): 
     for files in fi: 
      if files.startswith("data"): 
       with open(os.path.join(r, files), 'rb') as infh: 
        shutil.copyfileobj(infh, outfh) 
+0

감사합니다! – user3313975