在 Python 中以 ASCII 格式打开二进制文件
Open binary file as ASCII in Python
我想打开一个 ASCII 格式的二进制文件(是的,另一个软件合成器音库)并检查它是否包含字符串。文件夹中有多个文件,但我已经为它写了适当的代码,我只是想让它在文件中搜索一个子字符串。
我之前试过用ASCII编码功能打开同样的格式,但是显示的不是我想要的数据(显示的是一些乱码,和十六进制编辑器完全不一样,其中文件以 ASCII 打开)。有人能指出我正确的方向吗?
编辑:如下所述,这是我正在使用的新代码:
# sbf_check.py (sample code I've written to test the sbf file before implementing in into the main.py file)
path = "C:\Users\User\AppData\Roaming\RevealSound\Banks\Aura Qualic Trance.sbf"
file = open(path, "rb")
for x in file:
line = file.readline()
new = line.decode("ASCII")
print(new)
main.py 文件:
import glob, os
path = "C:\Users\User\AppData\Roaming\RevealSound\Banks"
for filename in glob.glob(os.path.join(path, "*.sbf")):
with open(os.path.join(os.getcwd(), filename), "r") as f:
# code to decode sbf file to ASCII, then search for the substring in the main string
十六进制编辑器:
(注:红色圈出的数据对我来说无所谓,因为是参数数据,我只是想搜索预设名称。不像我之前的问题,需要跳过参数数据。)
代码输出(VS Code):
Traceback (most recent call last):
File "c:\Users\User\Desktop\Programming\sbf_check.py", line 6, in <module>
new = line.decode("ASCII")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 0: ordinal not in range(128)
以下是您想要的吗?它应该通过显示豆腐盒而不是抛出解码错误来处理非 UTF-8 字符。
path = "C:\Users\User\AppData\Roaming\RevealSound\Banks\" \
"Aura Qualic Trance.sbf"
with open(path, errors='ignore') as f:
print(f.read())
我想打开一个 ASCII 格式的二进制文件(是的,另一个软件合成器音库)并检查它是否包含字符串。文件夹中有多个文件,但我已经为它写了适当的代码,我只是想让它在文件中搜索一个子字符串。
我之前试过用ASCII编码功能打开同样的格式,但是显示的不是我想要的数据(显示的是一些乱码,和十六进制编辑器完全不一样,其中文件以 ASCII 打开)。有人能指出我正确的方向吗?
编辑:如下所述,这是我正在使用的新代码:
# sbf_check.py (sample code I've written to test the sbf file before implementing in into the main.py file)
path = "C:\Users\User\AppData\Roaming\RevealSound\Banks\Aura Qualic Trance.sbf"
file = open(path, "rb")
for x in file:
line = file.readline()
new = line.decode("ASCII")
print(new)
main.py 文件:
import glob, os
path = "C:\Users\User\AppData\Roaming\RevealSound\Banks"
for filename in glob.glob(os.path.join(path, "*.sbf")):
with open(os.path.join(os.getcwd(), filename), "r") as f:
# code to decode sbf file to ASCII, then search for the substring in the main string
十六进制编辑器:
(注:红色圈出的数据对我来说无所谓,因为是参数数据,我只是想搜索预设名称。不像我之前的问题,需要跳过参数数据。)
代码输出(VS Code):
Traceback (most recent call last):
File "c:\Users\User\Desktop\Programming\sbf_check.py", line 6, in <module>
new = line.decode("ASCII")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 0: ordinal not in range(128)
以下是您想要的吗?它应该通过显示豆腐盒而不是抛出解码错误来处理非 UTF-8 字符。
path = "C:\Users\User\AppData\Roaming\RevealSound\Banks\" \
"Aura Qualic Trance.sbf"
with open(path, errors='ignore') as f:
print(f.read())