0

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?

3
  • @John, it makes it "b'Hello World'"
    – mowwwalker
    Commented Oct 2, 2011 at 22:09
  • I'm dumbfounded that this didn't get flagged as a possible duplicate and closed in seconds.
    – mowwwalker
    Commented Oct 2, 2011 at 22:11
  • 1
    Given that I sometimes feel that Python is growing too complex, and has grown too many conflicting ways of doing the exact same thing over the years, I am terribly pleased that we three produced textually the exact same answer to this question independently of each other. :) Commented Oct 2, 2011 at 22:20

3 Answers 3

6

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.

1
  • 1
    Thanks. It seems all three of you just about tied for the answer, but you got it first.
    – mowwwalker
    Commented Oct 2, 2011 at 22:11
5

You need to decode the bytes to text first.

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

Just decode the bytes:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.