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'" Commented Oct 2, 2011 at 22:09
  • I'm dumbfounded that this didn't get flagged as a possible duplicate and closed in seconds. 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

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It seems all three of you just about tied for the answer, but you got it first.
6

You need to decode the bytes to text first.

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

Comments

6

Just decode the bytes:

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.