开发者

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('My开发者_StackOverflow社区Text.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?


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.


You need to decode the bytes to text first.

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


Just decode the bytes:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜