Tutorials for writing Python scripts to get tag information for MP3 files

Source: Internet
Author: User
The following is a Python-based instance program to learn about Python. The purpose of this program is to analyze the tag information of all MP3 files and output them.
Import OS # Imports OS module, provides file path, lists 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 represents importing UserDict from the UserDict class, similar to import userdict.userdict in Java

def stripnulls (data): "An empty string of the processing function to replace all 00 bytes of content with a null character, the disease will be removed before and after the empty string" # Python strip used to remove the string of the beginning and end characters, in the same vein, Lstrip to remove the left character,  The Rstrip is used to remove the right character. Return Data.replace ("\00", "" "). Strip () class FileInfo (userdict):" File base class, store file name, inherit from UserDict (a class that stores Key-value, can rewrite _ _setitem__,__getitem__ method, you can use []) ' ' # Self is defined when used, do not need to use, if there is no parameter, then filename default to None, if there is a parameter, the parameter is the filename def __init_ _ (Self, Filename=none): userdict.__init__ (self) # Initialize parent class self["name"] = filename # set name to Filaname class Mp3fileinfo (FileInfo): "MP3 file information class, used to analyze MP3 files and store Information" # TAGDATAMAP the tag information used to store the MP3 location, (key: Start position, end position, processing function), # Stripnulls represents the first definition of the letter Number Tagdatamap = {"title": (3,, Stripnulls), "Artist": ((), Stripnulls), "album": (+,, stripnulls), "Ye Ar ": (Comment, 126, stripnulls)," Genre ": (" Stripnulls "): (127, +, ORD)} def __parse (self, Filena Me): # parsing MP3 file self.clear () Try:fsock = open (filename, "RB", 0) # Open a file try: # Set the file read pointer position, seek second        parameter, 2 means the end of the file as the reference point,# 128 means there is also a 128-byte end point, 0 means a reference point at the beginning of the file, 1 indicates the current position as a reference point Fsock.seek ( -128, 2) Tagdata = Fsock.read (128) # reads 128 bytes of data Finally:fsock.close () # Close file, note in Finally, error also need to close file handle if tagdata[:3] = = "Tag": # To determine if it is valid with TAG MP3 file # Follow Ring out the tag information location information, such as 3, Stripnulls, and then assign to start, end, Parsefunc for tag, (start, End, Parsefunc) in Self.tagDataMap.ite    MS (): # Tagdata[start:end] Read the byte of start to end, use Parsefunc to process the content self[tag] = Parsefunc (Tagdata[start:end])  Except IOError: # If IOError is present, skip the Continue pass # Override __setitem__ method, the above Self[tag] = Parsefunc (Tagdata[start:end]) will use this method, # key is tag,itme for Parsefunc (Tagdata[start:end]) def __setitem__ (self, Key, item): If key = = "Name" and item: # If key is NA  Me, and item is not empty Self.__parse (item) # Parse MP3 file # problem here,should out of the If # fileinfo.__setitem__ (self, Key, item) If you use this indentation there will be error # before the error point, note that the indentation here, anyway, will be stored key-value, using the Fileinfo.__setitem__ parent class method to store fileinfo.__setitem__ (SE LF, key, item) def ListDirectory (Directory, fileextlist): "Gets all fileextlist formatted files in directory directory, fileextlist is a list that can have multiple formats" fileList = [ Os.path.normcase (f) for F in Os.listdir (directory) # lists all directory files fileList = [Os.path.join (directory, F) for F in FileList # filters files to meet a format within the fileextlist. Os.path.splitext the file into file name and extension if Os.path.splitext (f) [1] in fileextlist] # sys.modules[fileinfo.__module__] Get Filei nfo.__module__ module, where fileinfo.__module__ is the main, # if it is called by another module is not, this is why not directly with "main" def getfileinfoclass (filename, MODULE=SYS.MODULES[FILEINFO.__MODULE__]): "Define a function to get the information of the file" # Gets the class that needs to be parsed, if the mp3 file result is Mp3fileinfo, the other is FileInfo SUBCL The "%sfileinfo"% os.path.splitext (filename) [1].upper () [1:] # Returns 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 (modules), which can be compared in this sentence Difficult to understand, Getfileinfoclass (f) (f) Why there are two (f), which has been said Getfileinfoclass (f) # Returns a parsing class based on the file name, where the return is Mp3fileinfo, and the second (f) Mp3fileinfo (f) return for this class with F initialization [GetfilEinfoclass (f) (f) for F in fileList] if __name__ = = "__main__": # main function, in other modules this code is not allowed in the for info in ListDirectory ("E:\ \music ", [". mp3 "]): # Loop to get information about all MP3 files in the E:\\music folder # because Mp3fileinfo inherits from Fileinfo,fileinfo inherits from UserDict, this items ()    is to get the Key-value collection.    # using "%s=%s" to format the output, use "\ n". Join joins all information in a newline. print "\ n". Join (["%s=%s"% (k, v) for K, V in Info.items ()]) print # After each file, output a blank line

The result is:

Album=what is Words-singlecomment=pythontabname=e:\music\chris medina-what_are_words.mp3title=what is Wordsartist =chris medinayear=2011genre=13 Album=after the Weddingcomment=pythontabname=e:\music\two fathers.mp3title=Two fathersartist=pythontabyear=2010genre=255


Note: Logic is more, the code is not small, do not understand the more read the comments

  • 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.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.