2014-02-15 31 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會嘗試將內容解碼爲Unicode。您通常需要爲文件指定正確的編解碼器(否則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