Skip to main content
 首页 » 编程设计

Python:在二进制文件 (.PLM) 中搜索 unicode 字符串

2025年04月02日29虾米哥

我正在尝试在 Windows 10 上使用 Python 2.7 从 .PLM 文件中提取目录名称。.PLM 文件是松下录音机使用的专有文件格式,它存储名称录音目录。

(例如:假设我有一个录音,我想将其保存在文件夹“HelloÆØÅ”中,然后这个录音机创建一个名为“SV_VC​​001”的文件夹和一个名为“SD_VOICE.PLM”的文件,其中,一堆其他数据,存储字符串“HelloÆØÅ”)

现在,我是丹麦人,所以使用字符 Æ、Ø 和 Å,这些字符不受 ascii 支持,因此我必须将此二进制数据转换为 unicode。

到目前为止,我知道目录的名称是从字节 56 开始存储的,并以全 0 的字节结束。例如,一个录音存储在名为“2-3-15 Årstids kredsløbet michael”的目录中,该目录具有十六进制值:

322d 332d 3135 20c5 7274 6964 7320 6b72  
6564 736c f862 6574 206d 6963 6861 656c 

这是我目前使用的代码:

# Finds the filename in the .PLM-file 
def  FindFileName(File): 
    # Opens the file and points to byte 56, where the file name starts 
    f = open(File,'rb') 
    f.seek(56) 
    Name = "" 
 
 
    byte = f.read(1)        # Reads the first byte after byte 56 
    while byte != "\x00":   # Runs the loop, until a NUL-character is found (00 is NUL in hex) 
        Name += str(byte)   # Appends the current byte to the string Name 
        byte = f.read(1)    # reads the next byte 
 
    f.close() 
 
    return Name 

这可行 - 前提是目录名称仅使用 ASCII 字符(因此没有“æ”、“ø”或“å”)。

但是,如果字符串中有 unicode 字符,则会将其转换为其他字符。对于目录“2-3-15 Årstids kredsløbet michael”,该程序输出“2-3-15 ┼rtids kredsl°bet michael”

你有什么建议吗?
非常感谢您。

编辑

加入Mark Ransom的建议,代码如下。我还笨拙地尝试处理发现的 3 种边缘情况:问号更改为空格,\xc5 和\xd8(分别为十六进制的 Å 和 Ø)分别更改为 å 和 ø。

def  FindFileName(File): 
    # Opens the file and points to byte 56, where the file name starts 
    f = open(File,'rb') 
    f.seek(56) 
    Name = "" 
 
 
    byte = f.read(1)        # Reads the first byte after byte 56 
    while byte and (byte != "\x00"):    # Runs the loop, until a NUL-character is found (00 is NUL in hex) 
 
        # Since there are problems with "?" in directory names, we change those to spaces 
        if byte == "?":  
            Name += " " 
        elif byte == "\xc5": 
            Name += "å" 
        elif byte == "\xd8": 
            Name += "ø" 
        else: 
            Name += byte 
 
    byte = f.read(1)    # reads the next byte 
 
f.close() 
 
return Name.decode('mbcs') 

对于大写的 Æ、Ø 和 Å 会产生以下错误:

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: u'C:\\Users\\UserName\\Desktop\\TestDir\\Mapper\\13-10*14 ESSOTERISK \xc5NDSSTR\xd8MNIN' 

字符串应为“13-10*14 ESSOTERISK ÅNDSSTRØMNIN”,但 Å 和 Ø(十六进制 c5 和 d8)会引发错误。

请您参考如下方法:

在 Python 2 中,读取二进制文件会返回一个字符串,因此无需在其上使用 str。此外,如果由于某种原因文件格式错误并且其中没有零字节,read 将返回一个空字符串。您可以通过对测试进行少量修改来检查这两种情况。

while byte and (byte != "\x00"):   # Runs the loop, until a NUL-character is found (00 is NUL in hex) 
    Name += byte        # Appends the current byte to the string Name 
    byte = f.read(1)    # reads the next byte 

一旦获得完整的字节序列,就必须将其转换为 Unicode 字符串。为此,您需要解码:

Name = Name.decode("utf-8") 

如评论中所述,您的字符串似乎实际上不是 UTF-8,而是 Microsoft 的代码页之一。您可以从 Windows 当前使用的代码页解码:

Name = Name.decode("mbcs") 

您可以显式提供一个代码页来代替使用,参见 the documentation .

尝试在控制台上打印字符串时可能会遇到麻烦,因为 Windows 控制台不使用与系统其余部分相同的代码页;它可能没有您需要打印的字符。