【问题标题】:Open binary file as ASCII in Python在 Python 中以 ASCII 格式打开二进制文件
【发布时间】:2021-04-24 21:47:09
【问题描述】:

我想打开一个 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)

【问题讨论】:

  • 你能举个具体的例子吗?
  • @xjcl 我要打开的文件是什么?这是一个 Spire 音库 (.sbf)。我不关心参数数据,我只想检查是否存在子字符串(预设名称)。我之前问过一个关于 Sylenth1 音库的类似问题,因此我没有写太多细节以避免它被标记为与我之前的问题重复。
  • 我的意思是你能在 hexedit 中显示一个示例文件以及你的代码输出什么吗?他们应该真的很匹配。
  • @xjcl 哦,当然。我会稍微修改一下。
  • @xjcl 现在应该没问题了,你能检查一下吗?

标签: python binaryfiles


【解决方案1】:

以下内容是否符合您的要求?它应该通过显示一个豆腐框而不是抛出解码错误来处理非 UTF-8 字符。

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

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

【讨论】:

  • 是的,确实如此!感谢您的帮助。
猜你喜欢
  • 2017-02-02
  • 1970-01-01
  • 2017-06-04
  • 1970-01-01
  • 2015-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多