[英]Open binary file as ASCII in Python
我想以 ASCII 格式打开一个二进制文件(是的,另一个软合成音库)并检查它是否包含字符串。 文件夹中有多个文件,但我已经为它编写了适当的代码,我只想让它在文件中搜索 substring。
我之前尝试过使用 ASCII 编码 function 打开相同的格式,但它没有显示我想要的数据(它显示一些乱码数据,与它在十六进制编辑器中所做的完全不同,其中文件以 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
(注:红色圈出来的数据对我来说无所谓,因为是参数数据,我只是想搜索预设的名称。不像我之前的问题,我需要跳过参数数据。)
代码 output(VS 代码):
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.