- #encoding=utf8
- __author__ ='pcode@qq.com'
- import os
- import struct
- def GetFiles(path):"""
- 读取指定目录的文件
- """FileDic=[]
- files=os.listdir(path)for f in files:
- f=f[:-4]FileDic.append(f)returnFileDic,files
- def GetLast128K(path,file):
- ff1=open(os.path.join(path,file),"rb")
- ff1.seek(-128,2)
- id3v1data=ff1.read()
- ff1.close()return id3v1data
- def GetAllBinData(path,file):
- ff1=open(os.path.join(path,file),"rb")
- data=ff1.read()
- ff1.close()return data
- def SetTag(path,file,title,artist,album,year,comment,genre):"""
- 设置mp3的ID3 v1中的部分参数
- char Header[3]; /*标签头必须是"TAG"否则认为没有标签*/
- char Title[30]; /*标题*/
- char Artist[30]; /*作者*/
- char Album[30]; /*专集*/
- char Year[4]; /*出品年代*/
- char Comment[30]; /*备注*/
- char Genre; /*类型*/
- mp3文件尾部128字节为id3v1的数据,如果有数据则读取修改,无数据则补充
- """
- header='TAG'#组合出最后128K的id3V1的数据内容
- str =struct.pack('3s30s30s30s4s30ss',header,title,artist,album,year,comment,genre)#获取原始全部数据
- data=_GetAllBinData(path,file)#获取末尾的128字节数据
- id3v1data=_GetLast128K(path,file)#打开原文件准备写入
- ff=open(os.path.join(path,file),"wb")try:#判断是否有id3v1数据if id3v1data[0:3]!=header:#倒数128字节不是以TAG开头的说明没有#按照id3v1的结构补充上去
- ff.write(data+str)else:#有的情况下要换一下
- ff.write(data[0:-128]+str)
- ff.close()print"OK"+title
- except:
- ff.write(data)print"Error "+title
- finally:
- if ff :
- ff.close()
- if __name__=="__main__":#我存放mp3文件的目录
- path=u"K:\\\\reading\\\\阅读\\\\东吴相对论"#获取到文件名和文件全名
- names,files=GetFiles(path)
- #苦力代码
- for i in range(len(files)):#注意编码解码
- title=names[i].encode('gbk')
- artist=u'梁冬 吴伯凡'.encode('gbk')
- album=u'东吴相对论'.encode('gbk')
- year=''
- comment=''
- genre=''#调用函数处理
- SetTag(path,files[i],title,artist,album,year,comment,genre)
- #该片段来自于http://www.codesnippet.cn/detail/130920135863.html
来源: http://www.codesnippet.cn/detail/130920135863.html