Open binary file as ASCII in Python

Viewed 606

I want to open a binary file (yes, another soft synth soundbank) in ASCII format and check if it contains a string or not. There are multiple files in the folder, but I have written the appropriate code for it, I just want it to search the file for a substring.

I've tried opening the same format using the ASCII encoding function before, but it does not display the data I want (it displays some garbled data, totally different from what it does in a hex editor, in which the file is opened in ASCII). Can someone point me in the right direction?

EDIT: As asked below, here is the new code I'm using:

# 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 file:

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

Hex editor: Image 1

Image 2

(Note: the data circled with red does not matter to me as it's parameter data, I just want to search for the preset name. It's not like my previous question, where I needed to skip the parameter data.)

Code output (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)
1 Answers

Does the following do what you want? It should handle non-UTF-8 characters by displaying a tofu box instead of throwing a decoding error.

path = "C:\\Users\\User\\AppData\\Roaming\\RevealSound\\Banks\\" \
       "Aura Qualic Trance.sbf"

with open(path, errors='ignore') as f:
    print(f.read())
Related