gpt4 book ai didi

python - Python-从二进制文件读取时如何删除 'b'?

转载 作者:行者123 更新时间:2023-12-03 09:12:42 26 4
gpt4 key购买 nike

我有以下简单文件:

This Was Actually Written In Binary

By Suraj Vijay



我有以下代码:
file = open("test.dat","rb")
lines=list()
for line in file.readlines():
lines.append(line.rstrip())
file.close()
print(lines)
print("File Reading Done")

这是我得到的输出:
 [b'This Was Actually Written In Binary', b'By Suraj Vijay']
File Reading Done

但是我不希望每个字符串的开头都是'b'(即我希望输出如下):
  ['This Was Actually Written In Binary', 'By Suraj Vijay']
File Reading Done

最佳答案

您只需解码“utf-8”中的行即可执行以下操作:

file = open("test.dat","rb")
lines=list()
for line in file.readlines():
lines.append(line.rstrip().decode("utf-8"))
file.close()
print(lines)
print("File Reading Done")

之所以得到 b,是因为它已编码为utf-8,现在它是一个字节对象。
print(type(line))
<class 'bytes'>

关于python - Python-从二进制文件读取时如何删除 'b'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61773308/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com