如何将字节转换为字符串,Python

时间:2017-12-10 08:10:27

标签: python string utf-8 byte decode

我正在尝试将字节转换/解码为字符串,我尝试过的代码如下所示:

body = ""
path = "C:\\Users\\...\\Demo"
listing = os.listdir(path)

for em in listing:
   mail = os.path.join(path, em)
   file = open(mail, 'rb')

   e_content = file.read()
   file.close()

   b = email.message_from_bytes(e_content)
   bbb = b['from']
   bbb = str(bbb)
   if '<' in bbb:
       bbb = bbb.split("<",1)[1]
       bbb = bbb[:-1]
       ccc = b['to']


   if b.is_multipart():
       for part in b.walk():
           ctype = part.get_content_type()
           cdispo = str(part.get('Content-Disposition'))

           # skip any text/plain (txt) attachments
           if ctype == 'text/plain' and 'attachment' not in cdispo:
               body = part.get_payload(decode=True)  # decode
               break


   else:
       body = b.get_payload(decode=True)


   mystring = str(body, 'utf-8','ignore')
   print(mystring)

不幸的是,这段代码出现了这个错误:

mystring = str(body, 'utf-8','ignore')
TypeError: decoding str is not supported

我该怎么做才能解决这个问题? 任何帮助表示赞赏。 :)

1 个答案:

答案 0 :(得分:1)

以下适用于Python 2.7.12和3.5.2:

body = b'<html>\n<body>\n<p>Some text</p></body></html>'
mystring = body.decode('utf-8')
print(mystring)

您的更新代码适用于Python 3.5.2但不适用于Python 2.7.12。