开发者

Python reading file in binary, binary data to string?

开发者 https://www.devze.com 2023-04-10 07:54 出处:网络
I\'m trying to learn Python and currently doing some exercises online. One of them involves reading zip files.

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

精彩评论

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