2

我昨天正在寻找一种扫描 mp3 元数据的方法,我在互联网上找到了这个代码片段

def getID3(filename):
    fp = open(filename, 'r') 
    fp.seek(-128, 2)
    fp.read(3) # TAG iniziale
    title   = fp.read(30)
    artist  = fp.read(30) 
    album   = fp.read(30) 
    fp.close()
    return {'title':title, 'artist':artist, 'album':album}

它完全有效,但问题是每次我使用它时,这个 ---> \x00<--- 都会出现在标题、专辑或艺术家的末尾。例如;

>>> import getid as id
>>> import os
>>> music = 'D:/Muzic'
>>> os.chdir(music)
>>> meta = id.getID3('04 - Mayday Parade - Your Song.mp3')
>>> meta
{'album': 'Tales Told By Dead Friends\x00\x00\x00\x00', 'artist': 'Mayday Parade\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', 'title': 'Your Song\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'}

任何人都知道如何摆脱它?

顺便说一句,我目前尝试的所有音乐都发生了这种情况。

4

2 回答 2

4

添加rstrip('\x00')到您读取文件的行:

fp.read(30).rstrip('\x00')

例子:

>>> 'abc\x00\x00\x00\x00'.rstrip('\x00')
'abc'
于 2012-06-01T12:04:46.490 回答
1

您正在读取一个固定的字段宽度 (30),并且该结构正在使用 null (\x00) 填充字段。

我认为您可以使用 .strip('\x00') 例如

   title   = fp.read(30).strip('\x00')
   artist  = fp.read(30).strip('\x00')
   album   = fp.read(30).strip('\x00')
于 2012-06-01T12:11:49.917 回答