Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何处理电子邮件包中的Python 3.x UnicodeDecodeError?_Python_Exception_Unicode_Python 3.x_Python Unicode - Fatal编程技术网

如何处理电子邮件包中的Python 3.x UnicodeDecodeError?

如何处理电子邮件包中的Python 3.x UnicodeDecodeError?,python,exception,unicode,python-3.x,python-unicode,Python,Exception,Unicode,Python 3.x,Python Unicode,我尝试从文件中读取电子邮件,如下所示: import email with open("xxx.eml") as f: msg = email.message_from_file(f) 我得到了这个错误: Traceback (most recent call last): File "I:\fakt\real\maildecode.py", line 53, in <module> main() File "I:\fakt\real\maildecode.p

我尝试从文件中读取电子邮件,如下所示:

import email
with open("xxx.eml") as f:
   msg = email.message_from_file(f)
我得到了这个错误:

Traceback (most recent call last):
  File "I:\fakt\real\maildecode.py", line 53, in <module>
    main()
  File "I:\fakt\real\maildecode.py", line 50, in main
    decode_file(infile, outfile)
  File "I:\fakt\real\maildecode.py", line 30, in decode_file
    msg = email.message_from_file(f)  #, policy=mypol
  File "C:\Python33\lib\email\__init__.py", line 56, in message_from_file
    return Parser(*args, **kws).parse(fp)
  File "C:\Python33\lib\email\parser.py", line 55, in parse
    data = fp.read(8192)
  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 0x81 in position 1920: character maps to <undefined>
回溯(最近一次呼叫最后一次):
文件“I:\fakt\real\maildecode.py”,第53行,在
main()
文件“I:\fakt\real\maildecode.py”,第50行,主目录
解码_文件(填充、输出文件)
文件“I:\fakt\real\maildecode.py”,第30行,在decode\u文件中
msg=email.message_from_file(f)#,policy=mypol
文件“C:\Python33\lib\email\\ uuuu init\uuuu.py”,第56行,在来自\u文件的消息\u中
返回解析器(*args,**kws.parse(fp)
解析中第55行的文件“C:\Python33\lib\email\parser.py”
数据=fp.read(8192)
文件“C:\Python33\lib\encodings\cp1252.py”,第23行,解码
返回编解码器.charmap\u解码(输入、自身错误、解码表)[0]
UnicodeDecodeError:“charmap”编解码器无法解码位置1920处的字节0x81:字符映射到
该文件包含一个多部分电子邮件,其中部分以UTF-8编码。文件的内容或编码可能已损坏,但我必须处理它

即使文件有Unicode错误,我如何读取该文件?我找不到policy对象
compat32
,似乎没有办法处理异常并让Python在异常发生的地方继续

我能做什么

with open('email.txt','rb') as f:
     ascii_txt = f.read().encode('ascii','backslashreplace')

with open('email.txt','w') as f:
     f.write(ascii_text)

#now do your processing stuff

我怀疑这是最好的处理方法。。。但这至少是一种方式…

我无法测试您的消息,所以我不知道这是否真的有效,但您可以自己解码字符串:

with open("xxx.eml", encoding='utf-8', errors='replace') as f:
    text = f.read()
    msg = email.message_from_string(f)

如果消息实际上不是UTF-8格式的,那么会有很多替换字符。但是如果它有
\x81
,我猜是UTF-8。

要在Python 3中解析没有unicode错误的电子邮件消息,请以二进制模式读取该文件,并使用
email.message\u from\u binary\u file(f)
(或
email.message\u from\u bytes(f.read())
)方法解析内容(请参阅)

下面是以与Python 2和3兼容的方式解析消息的代码:

import email
with open("xxx.eml", "rb") as f:
    try:
        msg = email.message_from_binary_file(f)  # Python 3
    except AttributeError:
        msg = email.message_from_file(f)  # Python 2

(使用Python2.7.13和Python3.6.0进行测试)

一种在Python3上工作的方法,可以找到编码并使用正确的编码重新加载

msg=email.message_from_file(open('file.eml',  errors='replace'))
codes=[x for x in msg.get_charsets() if x!=None]
if len(codes)>=1 : 
    msg=email.message_from_file(open('file.eml', encoding=codes[0]))

我试过使用
msg.get_charset()
,但当另一种编码可用时,它有时会回答
None
,因此稍微涉及编码检测

Hmm-但我想用电子邮件包处理它,而不是销毁所有UTF-8或它所在的任何字符集。尝试编码('UTF-8',“忽略”)。。。大概而不是('ascii')。但您需要打开文件以使用“wb”进行写入