mowwwalker
mowwwalker

Reputation: 17334

Python reading file in binary, binary data to string?

I'm trying to learn Python and currently doing some exercises online. One of them involves reading zip files.

When I do:

import zipfile
zp=zipfile.ZipFile('MyZip.zip')
print(zp.read('MyText.txt'))

it prints:

b'Hello World'

I just want a string with "Hello World". I know it's stupid, but the only way I could think of was to do:

import re
re.match("b'(.*)'",zp.read('MyText.txt'))

How am I supposed to do it?

Upvotes: 0

Views: 6476

Answers (3)

phihag
phihag

Reputation: 287755

Just decode the bytes:

print(zp.read('MyText.txt').decode('UTF-8'))

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

You need to decode the bytes to text first.

print(zp.read('MyText.txt').decode('utf-8'))

Upvotes: 5

Brandon Rhodes
Brandon Rhodes

Reputation: 89335

You need to decode the raw bytes in the string into real characters. Try running .decode('utf-8') on the value you are getting back from zp.read() before printing it.

Upvotes: 6

Related Questions