开发者

Wrong output using sample code from online book [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.

I'm having trouble with this Python code.. It's supposed to give me output similar to that shown here (should differ for different music files):

    album=
    artist=Ghost in the Machine
    title=A Time Long Forgotten (Concept
    genre=31
    name=/music/_singles/a_time_long_forgotten_con.mp3
    year=1999
    comment=http://mp3.com/ghostmachine

But instead gives me the following:

name = derp/whoshotya.mp3

Here is the code given to me (slightly modified to accommodate for the music sample I am using) in Chapter 5 of Dive Into Python, which can be found here:

"""Framework for getting filetype-specific metadata.

Instantiate appropriate class with filename.  Returned object acts like a dictionary, with key-value pairs for each piece of metadata.

import fileinfo
info = fileinfo.MP3FileInfo("/music/ap/mahadeva.mp3")
print "\\n".join(["%s=%s" % (k, v) for k, v in info.items()])

Or use listDirectory function to get info on all files in a directory.

for info in fileinfo.listDirectory("/music/ap/", [".mp3"]):
    ...

Framework can be extended by adding classes for particular file types, e.g. HTMLFileInfo, MPGFileInfo, DOCFileInfo. Each class is completely responsible for parsing its files appropriately; see MP3FileInfo for example.

This program is part of "Dive Into Python", a free Python book for experienced programmers. Visit http://diveintopython开发者_运维技巧.net/ for the latest version.

"""

__author__ = "Mark Pilgrim (mark@diveintopython.org)"
__version__ = "$Revision: 1.3 $"
__date__ = "$Date: 2004/05/05 21:57:19 $"
__copyright__ = "Copyright (c) 2001 Mark Pilgrim"
__license__ = "Python"

import os
import sys
from UserDict import UserDict

def stripnulls(data):
    "strip whitespace and nulls"
    return data.replace("\00", " ").strip()

class FileInfo(UserDict):
    "store file metadata"
    def __init__(self, filename=None):
        UserDict.__init__(self)
        self["name"] = filename

class MP3FileInfo(FileInfo):
    "store ID3v1.0 MP3 tags"
    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 ID3v1.0 tags from MP3 file"
        self.clear()
        try:
            fsock = open(filename, "rb", 0)
            try:
                fsock.seek(-128, 2)
                tagdata = fsock.read(128)
            finally:
                fsock.close()
            if tagdata[:3] == 'TAG':
                for tag, (start, end, parseFunc) in self.tagDataMap.items():
                    self[tag] = parseFunc(tagdata[start:end])
        except IOError:
            pass

    def __setitem__(self, key, item):
        if key == "name" and item:
            self.__parse(item)
        FileInfo.__setitem__(self, key, item)

def listDirectory(directory, fileExtList):
    "get list of file info objects for files of particular extensions"
    fileList = [os.path.normcase(f) for f in os.listdir(directory)]
    fileList = [os.path.join(directory, f) for f in fileList \
                if os.path.splitext(f)[1] in fileExtList]
    def getFileInfoClass(filename, module=sys.modules[FileInfo.__module__]):
        "get file info class from filename extension"
        subclass = "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:]
        return hasattr(module, subclass) and getattr(module, subclass) or FileInfo
    return [getFileInfoClass(f)(f) for f in fileList]

if __name__ == "__main__":
    for info in listDirectory("derp/", [".mp3"]):
        print "\n".join(["%s=%s" % (k, v) for k, v in info.items()])
        print


I think the problem may be here:

if __name__ == "__main__":
    for info in listDirectory("derp/", [".mp3"]):
        print "\n".join(["%s=%s" % (k, v) for k, v in info.items()])
        print

My thought is that the file in question (info) doesn't have all the file tags filled like the example does. That's why it's only showing the name field. Try manually changing the file tags (by right clicking the file and going to properties) and running the function again.

EDIT: I'm not sure exactly what's going on in your code, but I have a theory.

class MP3FileInfo(FileInfo):
    ...
    def __setitem__(self, key, item):
        if key == "name" and item:
            self.__parse(item)
        FileInfo.__setitem__(self, key, item)

This part is confusing me. What exactly happens here? It would seem like you would want to add the parsed data to the FileInfo object, wouldn't you? Where does this function get called from? And is key ever going to be anything other than "name", because that might be your problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜