2017-04-17 47 views
0

我正在尝试读取文件夹中的文件,并将每个文件的特定部分复制到使用下面的python code.but获取错误的新文件中从文件夹中读取大文件以复制到另一个文件时出现python错误

import glob 
file=glob.glob("C:/Users/prasanth/Desktop/project/prgms/rank_free1/*.txt") 
fp=[] 
for b in file: 
    fp.append(open(b,'r')) 
s1='' 
for f in fp: 
    d=f.read().split('\t') 
    rank=d[0] 
    appname=d[1] 
    appid=d[2] 
    s1=appid+'\n' 
file=open('C:/Users/prasanth/Desktop/project/prgms/appids_file.txt','a',encoding="utf-8") 
    file.write(s1) 
    file.close() 

即时得到以下错误消息

enter code here 
Traceback (most recent call last): 
File "appids.py", line 8, in <module> 
d=f.read().split('\t') 
File "C:\Users\prasanth\AppData\Local\Programs\Python\Python36- 
32\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 0x8f in position 
12307: character maps to <undefined> 

回答

0

从我可以看到您打开包含非UTF8字符,所以也没有关于适当的信息被读入一个字符串变量中的一个文件其编码。

要处理这个问题,您需要打开文件以二进制模式阅读并在脚本中处理该问题。

您可以放入d=f.read().split('\t')进行尝试:除了:在except:分支中构造并以二进制模式重新打开该文件。然后在脚本中处理它包含的非UTF8字符的问题。

相关问题