首页 > 解决方案 > 如何使用 Python 读取带有 NULL 字符的二进制文件

问题描述

我正在尝试读取数据库的二进制文件并使用 python 解析它。从来没有用 python 做过这样的事情,并且在处理“混乱”数据时遇到了一些麻烦。数据中有一堆 NULL 值,我不确定如何在不检查 NULL 终止符的情况下逐字节读取文件。

如何读取包含所有这些混乱值的文件?

我正在使用此方法从打开的文件缓冲区中获取可变数量的字节(我不知道这是否是正确的名称,但我会file = open(file_path, "rb")在文件上调用此函数之前调用它。

    def getBytes(self, file, numBytes):

      bArray = file.read(numBytes)
      x=0
      while x < numBytes:

        if (bArray[x] < 32) or (bArray[x] > 126):
          bArray[x] = 32
        x+=1

      charArray = bArray.decode("utf-8")

      self.buffer += numBytes

      return charArray

即使只测试没有特殊字符的 uft-8 字符串,我也会收到此错误。所以这绝对不是一个很好的实现。

Traceback (most recent call last): File "D:\projects\git\pgdump_parser\src\python\PG_Dump_Parser\Source_Code\main.py", line 3, in <module> Sp = Parser.Parser("./PG_Dump_Parser/Data/small_data.txt") File "D:\projects\git\pgdump_parser\src\python\PG_Dump_Parser\Source_Code\Parser.py", line 17, in __init__ self.inData = self.getEntities() File "D:\projects\git\pgdump_parser\src\python\PG_Dump_Parser\Source_Code\Parser.py", line 66, in getEntities found = self.findNextCREATE(file) File "D:\projects\git\pgdump_parser\src\python\PG_Dump_Parser\Source_Code\Parser.py", line 34, in findNextCREATE byte = self.getBytes(file, 1) File "D:\projects\git\pgdump_parser\src\python\PG_Dump_Parser\Source_Code\Parser.py", line 97, in getBytes print("bArrayOld: %s \nx: %s" % (bArray[x], x)) IndexError: bytearray index out of range

标签: pythonparsingutf-8

解决方案


如果你想用空格替换某些字符,使用该translate方法更容易。

(请注意,self.buffer应该使用您实际读取的字节数进行更新,而不是您尝试读取的字节数。)

not_printable_ascii = bytes(range(32)) + bytes(range(127, 256))
spaces = b' ' * len(non_printable_ascii)
trans_table = bytes.maketrans(not_printable_ascii, spaces)

def getBytes(self, file, numBytes):
    bArray = file.read(numBytes)
    self.buffer += len(bArray)
    return bArray.translate(trans_table).decode("utf-8")

推荐阅读