gonzalloe
gonzalloe

Reputation: 313

How to convert byte to string, Python

I am trying to convert/decode byte to string and the code I've tried is shown as below:

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)

Unfortunately, this code came out with this error:

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

What should I do to fix this? Any help is appreciated. :)

Upvotes: 2

Views: 4814

Answers (1)

R Sahu
R Sahu

Reputation: 206717

The following works for me with Python 2.7.12 and 3.5.2:

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

Your updated code works for me with Python 3.5.2 but not with Python 2.7.12.

Upvotes: 3

Related Questions