Python instance obtains the tag information of mp3 files

Source: Internet
Author: User
The Python instance obtains the tag information of an mp3 file and uses a python instance program to learn python. The purpose of this program is to analyze the Tag information of all MP3 files and output them.

Import OS # import OS module, provide file paths, list files, and other methods import sys # import sys module, use sys. modules gets all the content in the module, similar to the reflection function from UserDict import UserDict # This indicates to import UserDict from the UserDict class, similar to the import UserDict in Java. userDict def stripnulls (data): "an empty string handler replaces all 00 bytes with null characters, remove the null string before and after the disease "# strip in Python is used to remove the first and last characters of the string. Similarly, lstrip is used to remove the character on the left, and rstrip is used to remove the character on the right. Return data. replace ("\ 00 ",""). strip () class FileInfo (UserDict): ''' file base class, the file name of the stored file, inherited from UserDict (a class that stores key-value, you can override _ setitem __, __getitem _ method, you can use [] ''' # self is used for definition and is not required for use. if there is no parameter, filename is set to None by default, if there is a parameter, it is filename def _ init _ (self, filename = None): UserDict. _ init _ (self) # Initialize the parent class self ["name"] = filename # set name to filaname class MP3FileInfo (FileInfo): "MP3 file information class, used to analyze MP3 files and storage information "# tagDataMap Location where the MP3 Tag information is stored (key: start location, end location, processing function), # stripnulls indicates the function tagDataMap = {"title": (3, 33, stripnulls), "artist": (33, 63, stripnulls), "album": (63, 93, stripnulls), "year": (93, 97, stripnulls), "comment": (97,126, stripnulls), "genre": (127,128, ord)} def _ parse (self, filename): # parse MP3 file self. clear () try: fsock = open (filename, "rb", 0) # open the file try: # set the pointer position for file reading, second parameter of seek, 2 indicates that the end of the file is used as the reference point, #-128 indicates that there are still points at the end of 128 bytes, 0 indicates that the start of the file is used as the reference point, and 1 indicates that the current position is used as the reference point fsock. seek (-128, 2) tagdata = fsock. read (128) # read 128 bytes of data finally: fsock. close () # close the file. Note that in finally, you must close the file handle if tagdata [: 3] = "TAG ": # determine whether an MP3 file with tags is valid # cyclically retrieve Tag information location information, such as 3, 33, stripnulls, and assign them to start, end, parseFunc for Tag, (start, end, parseFunc) in self. tagDataMap. items (): # tagdata [start: end] reads the byte from start to end, and uses parseFunc to process the content self [Tag] = parseFunc (tagdata [start: end]) handle T IOError: # if an IOError occurs, skip the Continue pass # override _ setitem _ method, the above self [tag] = parseFunc (tagdata [start: end]) will use this method, # key is tag, itme is 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) # parse MP3 files # problem here, shoshould out of the if # FileInfo. _ setitem _ (self, key, item) if this indent is used, an error occurs. Error # Previous error point. Note the indentation here. the key-value will be stored in any case and FileInfo will be used. _ setitem _ parent class method to store FileInfo. _ setitem _ (self, key, item) def listDirectory (directory, fileExtList): "gets all fileExtList files in the directory. fileExtList is a list, there can be 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 in fileExtList. OS. path. splitext divides the file into file names and extensions if OS. path. splitext (f) [1] in fileExtList] # sys. modules [FileInfo. _ module _] get FileInfo. _ module, where FileInfo. _ module _ here it will be main. # if it is called by another module, it will not be. This is why "main" def getFileInfoClass (filename, module = sys. modules [FileInfo. _ module _]): "defines a function to obtain file information" # obtains the class to be parsed. if the mp3 file returns MP3FileInfo, fileInfo subclass = "% sFileInfo" % OS. path. splitext (filename) [1]. upper () [1:] # Return a class. Note that a "class" is returned ". Use getattr to obtain the subclass class return hasattr (module, subclass) and getattr (module, subclass) or FileInfo in the moudle module # Note: This sentence may be hard to understand. getFileInfoClass (f) (f) why are there two (f) statements? as mentioned above, getFileInfoClass (f) # returns a parsing class based on the file name. here the returned class is MP3FileInfo, and the second (f) it indicates that this class is initialized with f MP3FileInfo (f) return [getFileInfoClass (f) for f in fileList] if _ name _ = "_ main _": # main function, the code for info in listDirectory ("E: \ Music ",[". mp 3 "]): # cyclically obtain information about all mp3 files in the E: \ Music folder # because MP3FileInfo inherits from FileInfo, FileInfo inherits from UserDict, this items () is to obtain the key-value set. # Format the output using "% s = % s" and use "\ n". join to concatenate all information with line breaks. Print "\ n ". join (["% s = % s" % (k, v) for k, v in info. items ()]) print # output a blank line after each file

Result:

Album = What Are Words-Single

Comment = pythontab

Name = E: \ Music \ chris medina-what_are_words.pdf

Title = What Are 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: There are many logics and few codes. you can read comments without understanding them.

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.