A tutorial on writing Python scripts to get MP3 file tag information

Source: Internet
Author: User
Tags comments join python script

This article mainly introduces the writing Python script to obtain MP3 file tag information tutorial, the code is based on python2.x, the text of the comments in detail, the need for friends can refer to the

Here's how to learn python using a Python instance program. The purpose of this program is to analyze the tag information of all MP3 files and output it.

Import OS # importing OS modules, providing file paths, listing files, and other methods

Import SYS # imports the SYS module, using Sys.modules to get all the content in the module, similar to the reflection function

From userdict Import UserDict # This representation imports userdict from the UserDict class, similar to the import userdict.userdict in Java


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 45, 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 def stripnulls (data): "The processing function of an empty string replaces all 00 bytes of content with empty characters, and sickness removes the empty string before and after" # The strip in Python is used to remove the end-and-end character of the string, and Lstrip is used to remove characters from the left. Rstrip is used to remove the character on the right. return Data.replace ("0", ""). Strip ()   class FileInfo (userdict): ' The file base class, which stores the file name, inherits from UserDict (a class that stores Key-value, You can override the __setitem__,__getitem__ method, you can use []] ' # Self is defined when used, no need, if no parameters, filename default None, if there is a parameter, the parameter is filename def __ Init__ (self, Filename=none): userdict.__init__ (self) # initializes the parent class self["name" = filename # set name to Filaname   class Mp3fi Leinfo (FileInfo): "MP3 File information class for analyzing MP3 file and storage Information" # Tagdatamap the location of the tag information used to store MP3, (key: Start position, end position, handler function), # Stripnulls represents the most initially defined function Tagdatamap = {"title": (3, Stripnulls), "Artist": (M, S, Stripnulls), "album": (A. tripnulls), "Year": (Stripnulls, Stripnulls, genre), "comment": (127), "128": (126)}   def Ord RSE (self, filename): # parsing MP3 file self.clear () Try:fsock = open (filename, RB, 0) # Open File try: # Set the position of the pointer read by the file, seek the second parameter, 2 indicates the The end of the file as a reference point, #-128 indicates that there are 128 bytes at the end of the point, 0 means the beginning of the file as a reference point, 1 means that whenFront position make reference point Fsock.seek ( -128, 2) Tagdata = Fsock.read (128) # Read 128 bytes of data finally:fsock.close () # Close file, note in Finally, error also need to close file handle I F Tagdata[:3] = = "TAG": # To determine whether it is valid with tag MP3 file # loop out the tag information location information, such as 3, Stripnulls, and then assigned to start, end, Parsefunc for TAG, (star T, end, Parsefunc) in Self.tagDataMap.items (): # Tagdata[start:end] read out the bytes of start to finish, use Parsefunc to process the content self[tag] = Parsefunc (Tagdata[start:end]) except IOError: # If IOError is present, skip continuation pass   # rewrite __setitem__ method, above self[tag] = Parsefunc (Tagdata[start:end]) will use this method, # key for Tag,itme for Parsefunc (Tagdata[start:end]) def __setitem__ (self, Key, item): If key = = " Name and item: # If key is name and item is not empty Self.__parse (item) # resolves MP3 file # problem here,should out of the If # Fileinfo.__set Item__ (self, key, item) If you use this indentation, you will see the error point before the error #, note that the indentation here, in any case, will store the Key-value, using the fileinfo.__setitem__ method of the parent class to store the fileinfo.__ Setitem__ (self, key, item)   DEF listdirectory (directory, fileextlist): "Get all Files in fileextlist format in the directory directory, Fileextlist is a list that can have multiple formats "filelist = [os.path.normcase(f) for F in Os.listdir (directory)] # list all directory files filelist = [Os.path.join (directory, F) for F in FileList # Filter files to meet A format within the fileextlist. Os.path.splitext file into file name and extension if Os.path.splitext (f) [1] in fileextlist]   # sys.modules[fileinfo.__module__] Get the fileinfo.__module__ module where fileinfo.__module__ will be main, # if it's not called by another module, why not just use the "main" Def Getfileinfoclass ( FileName, module=sys.modules[fileinfo.__module__]): "Define a function, get the information of the file" # Get the class that needs to be parsed, if the mp3 file results in Mp3fileinfo, Others are fileinfo subclass = "%sfileinfo"% os.path.splitext (filename) [1].upper () [1:] # Return a class, note that a "class" is returned. Use GetAttr to get the subclass class return Hasattr (module, subclass) and GetAttr (module, subclass) or FileInfo # in the Moudle module note that This sentence may be more difficult to understand, Getfileinfoclass (f) (f) Why there are two (f), which has been said Getfileinfoclass (f) # Returns a parsing class based on the filename, here is the return is Mp3fileinfo, and the second (f) This class is initialized with F Mp3fileinfo (f) return [Getfileinfoclass (f) (f) to F in filelist]   if __name__ = = "__main__": # main function, in This code is not allowed in the other modules for info in listdirectory ("E:music", [". mp3"]): # Looping to get the E:music folderSome mp3 file information # Because Mp3fileinfo inherits from Fileinfo,fileinfo inherits from UserDict, the items () of this are get Key-value collection. # use '%s=%s ' to format the output, using ' n '. Join to connect all the information to a newline. Print "n". Join (["%s=%s"% (k, v) for K, V in Info.items ())] Print # After each file, output a blank line

The results are:


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 Album=what Are words-single comment=pythontab name=e:musicchris medina-what_are_words.mp3 title=What Are Words Artist=chris Medina year=2011 genre=13 album=after the wedding comment=pythontab name=e:musictwo fathers.mp 3 Title=two Fathers Artist=pythontab year=2010 genre=255

Note: The logic is more, the code is not too small, do not understand more read comments

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.