omr*_*hur 2 python zip file zipfile
在下面的代码中,我总是得到一个奇怪的输出,它将b放在每一行之前。只是字母b。
例如,示例输出如下:
[b'2017-06-01,15:19:57,']
Run Code Online (Sandbox Code Playgroud)
脚本本身是这样的:
from zipfile import ZipFile
with ZipFile('myarchive.zip','r') as myzip:
with myzip.open('logs/logfile1.txt') as myfile:
next(myfile)
print(myfile.readlines())
Run Code Online (Sandbox Code Playgroud)
归档文件中有一个名为“日志”的文件夹,日志中有几个文本文件,每个文本文件的第一行都为空(因此, next(myfile)
无论我尝试读取哪个文件,它都会在数据前放置b。如果文件中有多行,它将输出如下内容:
[b'2017-06-01,15:06:28,start session: \n', b'2017-06-01,15:06:36,stop session']
Run Code Online (Sandbox Code Playgroud)
为什么将讨厌的b放在那儿?
在Python 3.x中,字符串和字节数据之间存在区别。当将字节表示为字符串时,Python添加b前缀来表示这一点。如果要将您bytes视为字符串,则首先需要将它们解码为字符串:
your_string = your_bytes.decode("utf-8")
Run Code Online (Sandbox Code Playgroud)
当然,您将使用的编解码器首先取决于将字符串编码为字节的方式。
| 归档时间: |
|
| 查看次数: |
1854 次 |
| 最近记录: |