# -*- coding: cp936 -*-
"""
用于批量转换特定目录下所有MP3名称(包括改目录下所有子目录),新名称格式:“演唱者-歌曲名称”。
Mp3文件格式:
at end of file - 128 bytes
offset type len name
--------------------------------------------
0 char 3 "TAG"
3 char 30 title
33 char 30 artist
63 char 30 album
93 char 4 year
97 char 30 comments
127 byte 1 genre
--------------------------------------------
"""
import sys
import os
import os.path
class MP3INFO:
"""读取mp3文件中的演唱者和歌曲名称信息"""
def __init__(self, filename):self.title = ''
self.artist = ''
f = file(filename,'rb')
f.seek(-128,2)
s=f.read(3)
if s == 'TAG': # 判断是否是mp3文件
strlist = []
for i in (30,30):
s = f.read(i)
pos = s.find('/0')
if pos == 0:
s = ''
elif pos > 0:
s = s[0:pos]
strlist.append(s.strip())
self.title, self.artist = strlist
f.close()
def RenameMp3File(arg,dirname,names):
"""dirname: 目录名;names:目录下所有文件列表"""
for name in names:
filename = dirname + '/' + name
if os.path.isdir(filename) or name[-3:].lower() != 'mp3':
pass #该文件如果是目录或不是.mp3文件,则什么也不作
else:
mp3 = MP3INFO(filename)
#拼装新的文件名
if mp3.title == '':
mp3filename = name
elif mp3.artist == '':
mp3filename = mp3.title + '.mp3'
else:
mp3filename = mp3.artist + ' - ' + mp3.title + '.mp3'
#消除新文件名中的非法字符
a = '//:*?"<>|'t = [ x for x in mp3filename if x not in a]
mp3filename = ''
for x in t:
mp3filename += x
#如果是在winxp下,无需判断字符编码
#linux下需要将原来的字符编码格式转换为UTF8的格式,否则显示乱码
'utf-8', 'utf-16', 'big5-hkscs','iso-2022-cn',/
'iso-2022-jp', 'iso-2022-kr', 'iso-8859-1']
#codelist = ['utf-8', 'gbk', 'big5', 'iso-8859-1']
for code in codelist:
try:
mp3filename = unicode(mp3filename, code)
mp3filename = mp3filename.encode('utf-8')
# Judge that mp3.title not empty, because destination
# filename will be equal to source filename when mp3.title
# is empty. If not, it will throw OSError: duplication of
# filename when run 'os.rename(...)'
if mp3.title != '' and mp3filename != name:
os.rename(filename, dirname + '/' + mp3filename)
print code, '---', filename, ' --> ', mp3filename
break
except OSError:
print 'duplication of name: ',filename
pass
except:
if code == codelist[-1]:
print code, '---', filename, ' ---', mp3filename
print "Unexpected error:", sys.exc_info()[0]
pass
if __name__ == '__main__':
p=r'/home/ljh/MyMusic'
if len(sys.argv) > 1:
p = sys.argv[1]
os.path.walk(p, RenameMp3File,0)