本文实例讲述了Python编程修改MP3文件名称的方法。分享给大家供大家参考,具体如下:
最近刚刚开始学习Python,顺便锻炼思维写的一个小函数,专门用来修改那些网上下载的mp3歌曲后名称不正确时候,使用该函数,使用方法
1
|
ModifyMp3FileInfo(r 'E:/音乐/12345.mp3' )
|
Python代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
#!修改下载的Mp3文件名称为正确的Mp3文件
def ModifyMp3FileInfo(filename):
mp3Id3V1 = {
"tag" :{ "valuepos" :( 0 , 3 ), "value" :""},
"SongName" :{ "valuepos" :( 3 , 33 ), "value" :""},
"SongPeople" :{ "valuepos" :( 33 , 63 ), "value" :""},
"Zj" :{ "valuepos" :( 63 , 93 ), "value" :""},
"Year" :{ "valuepos" :( 93 , 97 ), "value" :""},
"Bak" :{ "valuepos" :( 97 , 125 ), "value" :""}
}
try :
f = open (filename, 'rb' )
f.seek( - 128 , 2 )
sdata = f.read( 3 )
if sdata = = 'TAG' :
f.seek( - 128 , 2 )
sdata = f.read( 128 )
for tag,subitem in mp3Id3V1.items():
subitem[ "value" ] = sdata[subitem[ "valuepos" ][ 0 ]:subitem[ "valuepos" ][ 1 ]].replace( '/00' ,'').strip()
print '%s=' % tag, '%s' % subitem[ "value" ], '/n'
f.close()
import os
if mp3Id3V1[ "SongName" ][ "value" ]! = '':
test = [os.path.dirname(filename), '//' ]
test.append(mp3Id3V1[ "SongName" ][ "value" ])
test.append( '.mp3' )
newfilename = ''.join(test)
print newfilename
if os.path.exists(newfilename):
test = [ 'Filename ' ,newfilename, ' Has Existed' ]
print ''.join(test)
else :
try :
os.rename(filename,newfilename)
except WindowsError,e:
if e.winerror:
print 'Modify filename failed ,maybe the file is inuse'
else :
print 'UnKnown error'
else :
print 'Is not a MP3 file'
except IOError:
print 'Open file failed'
|
希望本文所述对大家Python程序设计有所帮助。