【问题标题】:Python: Convert data file format to stringPython:将数据文件格式转换为字符串
【发布时间】:2021-11-09 11:31:09
【问题描述】:

file 命令运行时,我有一个具有以下输出的文件:

#file test.bin
#test.bin : data

#file -i test.bin
#test.bin: application/octet-stream; charset=binary

我想读取这个文件的内容并转发到一个接受这个读取数据作为字符串的python库。

        file = open("test.bin", "rb")
        readBytes = file.read()            # python type : <class 'bytes'>
        
        output = test.process(readBytes)   # process expects a string

我试过str(readBytes),但是没有用。我看到文件test.bin 中也有不可打印的字符串,因为strings test.bin 的输出产生的输出比文件中存在的实际字节少得多。

有没有办法将读取的字节转换为字符串?还是我试图实现一些毫无意义的事情?

【问题讨论】:

  • 只是不要将其读取为字节。 file = open("test.bin", "r")
  • @DavidMeu :我以前试过这个,它给了我以下错误。 UnicodeDecodeError: 'utf-8' codec can't decode byte 0x88 in position 18: invalid start byte。正在读取的文件是加密的密钥材料。我想读取文件数据并将其转发到 python 库。

标签: python string file character-encoding


【解决方案1】:

尝试使用位串。这是读取位的好包。

# import module
from bitstring import ConstBitStream

# read file
x = ConstBitStream(filename='file.bin')

# read 5 bits
output = x.read(5)

# convert to unsigned int
int_val = output.uint

【讨论】:

  • 这可行,但我观察到以下内容:使用os.path.getsize("test.bin")= 3581 bytes 获得的文件大小。执行上述步骤后读取的字节数 = 8623.output = x.read(3581*8)。这是预期的行为吗?
  • 如果你已经从一个 1 GB 的文件对象初始化了一个位串并要求它的二进制字符串表示,那么这个字符串的大小大约是 8 GB。这是程序的预期行为。就计算和内存要求而言,这些属性可能非常昂贵,因此您必须了解您在内存中所做的事情。
  • 我的意思是,len(str(output.uint)) = 8623。我不明白为什么字符串长度不是3581*8
【解决方案2】:

你的意思是?

output = test.process(readBytes.decode('latin1'))

【讨论】:

  • 它给出了与上面评论中提到的相同的错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0x88 in position 18: invalid start byte
  • @gst 编辑了我的答案
猜你喜欢
  • 2015-01-10
  • 1970-01-01
  • 2019-03-14
  • 2013-02-04
  • 1970-01-01
  • 1970-01-01
  • 2020-12-15
  • 2014-02-18
  • 2012-02-14
相关资源
最近更新 更多