python - 如何使用 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
解决方案
如果你想用空格替换某些字符,使用该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")
推荐阅读
- javascript - 如何使用 JSDoc 命名参数
- angular - 如何使用 Angular 并行执行 API
- python - wagtail 的现有 Django 站点实现。如何让 RichTextField 在管理员中显示?
- vue.js - 如何在Vue中访问Transition块内的元素
- apache-kafka - 如何找到 confluent sftp 连接器的剩余试用期?
- php - 递归删除功能不会删除名称中带有大括号的文件夹
- azure - 使用 txt 文件中的数据附加 SQL 数据库
- string - 如何快速计算字符串中连续单个字符的最大数量?
- python - FastAPI 解析 HTTP GET 列表
- python-3.x - 滚动浏览 tkinter 中的多个图像