Python programming method to modify the name of the MP3 file

  • 2020-05-30 20:28:38
  • OfStack

This article illustrates how the Python program can modify the MP3 file name. I will share it with you for your reference as follows:

Recently, I have just started to learn Python. By the way, I have exercised my mind to write a small function, which is specially used to correct the name of mp3 songs downloaded from the Internet


ModifyMp3FileInfo(r'E:/ music /12345.mp3')

Python code:


#! Modify downloaded Mp3 The file name is called correct Mp3 file 
 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'

More about Python related topics: interested readers to view this site "Python file and directory skills summary", "Python skills summary text file", "Python URL skills summary", "Python pictures skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using skills summary", "Python string skills summary" and "Python introductory and advanced tutorial"

I hope this article is helpful to you Python programming.


Related articles: