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 contents of the module, similar to the reflection function from userdict Import UserDict # This representation Import UserDict from the UserDict class, similar to import userdict.userdict def stripnulls (data) in Java: "An empty string's handler replaces all 00 bytes of content with a null character, The empty string before and after the disease is removed "# python strip is used to remove the beginning and end characters of a string, in the same vein, Lstrip is used to remove the left character, Rstrip 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 __ini T__ (self, Filename=none): userdict.__init__ (self) # Initialize parent class self["name"] = filename # set name to Filaname class Mp3fileinfo (FileInfo): "MP3 File information class for parsing MP3 files and storing information" # Tagdatamap the location where the tag information for the MP3 is stored, (key: Start position, end position, processing function), # St Ripnulls represents the first definition of the function Tagdatamap = {"title": (3,, Stripnulls), "Artist": ((),, Stripnulls), "album": (63 , Stripnulls), "Year": (Stripnulls, Comment): (97, 126, Stripnulls), "genre": (127, T, Ord)} def __parse (self, filename): # parse MP3 file self.clear () t Ry:fsock = open (filename, "RB", 0) # Opens a file try: # Sets the pointer position of the file read, seek the second argument, 2 indicates the end of the file as a reference Point, # 128 means there is also a 128-byte end point, 0 means that the file starts with a reference point, and 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 the file, note that in Finally, an error also requires closing the file handle if Tagdata[:3] = = "Tag": # To determine if a valid MP3 file containing the tag # loop 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.items (): # Tagdata[start:end] Read start To end bytes, use Parsefunc to process these contents self[tag] = Parsefunc (Tagdata[start:end]) except IOError: # if Ioerro is present R, then skip continue pass # Override __setitem__ method, 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 name and item is not empty self.__p Arse (item) # Parse MP3 file # problem here,should out of the If # fileinfo.__setitem__ (self, key, item) if the With 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__ (self, 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 # Filter file, satisfies a format within fileextlist. Os.path.splitext the 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__ is the main, # if it is called by another module, it is not, this is why not directly with the "main" Def Getfileinfoclass (f Ilename, module=sys.modules[fileinfo.__module__]): "Defines a function that receivesFetch the file information "# Gets the class that needs to be parsed, if the mp3 file result is Mp3fileinfo, the other is fileinfo subclass ="%sfileinfo "% os.path.splitext (filename ) [1].upper () [1:] # Returns a class, notice 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, which The sentence may be 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) It means that the class is initialized with F Mp3fileinfo (f) return [Getfileinfoclass (f) (f) to F in fileList] if __name__ = = "__main__": # main function, in other modulo The block will not allow this inside the code for the For info in listdirectory ("E:\\music", [". mp3"]): # Loop to get information about all MP3 files in the E:\\music folder # due to Mp3fileinfo inheritance Since Fileinfo,fileinfo inherits from UserDict, this is the items () that gets 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-single
Comment=pythontab
Name=e:\music\chris Medina-what_are_words.mp3
Title=what is Words
Artist=chris Medina
year=2011
Genre=13
Album=after The Wedding
Comment=pythontab
Name=e:\music\two Fathers.mp3
Title=two Fathers
Artist=pythontab
year=2010
genre=255
Note: Logic is more, the code is not small, do not understand the more read the comments