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?
asked Oct 2, 2011 at 22:02
mowwwalker
17.5k30 gold badges109 silver badges166 bronze badges
-
@John, it makes it "b'Hello World'"mowwwalker– mowwwalker2011年10月02日 22:09:41 +00:00Commented Oct 2, 2011 at 22:09
-
I'm dumbfounded that this didn't get flagged as a possible duplicate and closed in seconds.mowwwalker– mowwwalker2011年10月02日 22:11:23 +00:00Commented Oct 2, 2011 at 22:11
-
1Given 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. :)Brandon Rhodes– Brandon Rhodes2011年10月02日 22:20:33 +00:00Commented Oct 2, 2011 at 22:20
3 Answers 3
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.
answered Oct 2, 2011 at 22:05
Brandon Rhodes
91.1k16 gold badges110 silver badges149 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
mowwwalker
Thanks. It seems all three of you just about tied for the answer, but you got it first.
You need to decode the bytes to text first.
print(zp.read('MyText.txt').decode('utf-8'))
answered Oct 2, 2011 at 22:06
Ignacio Vazquez-Abrams
804k160 gold badges1.4k silver badges1.4k bronze badges
Comments
lang-py