Python读取二进制文件,二进制数据转字符串?
我正在尝试学习 Python,目前正在网上做一些练习。其中之一涉及读取 zip 文件。
当我这样做时:
import zipfile
zp=zipfile.ZipFile('MyZip.zip')
print(zp.read('MyText.txt'))
它打印:
b'Hello World'
我只想要一个带有“Hello World”的字符串。我知道这很愚蠢,但我能想到的唯一方法就是:
import re
re.match("b'(.*)'",zp.read('MyText.txt'))
我该怎么做?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要将字符串中的原始字节解码为真实字符。在打印之前,尝试对从
zp.read()
返回的值运行.decode('utf-8')
。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 fromzp.read()
before printing it.您需要首先将字节解码为文本。
You need to decode the bytes to text first.
只需解码字节:
Just decode the bytes: