Posted on 2009-07-27 16:54
Hero 阅读(198)
评论(0) 编辑 收藏 引用 所属分类:
C#积累
1 import os
2 import sys
3 from UserDict import UserDict
4
5 def stripnulls(data):
6 "strip whitespace and nulls"
7 return data.replace("\00", " ").strip()
8
9 class FileInfo(UserDict):
10 "store file metadata"
11 def __init__(self, filename=None):
12 UserDict.__init__(self)
13 self["name"] = filename
14
15 class MP3FileInfo(FileInfo):
16 "store ID3v1.0 MP3 tags"
17 tagDataMap = {"title" : ( 3, 33, stripnulls),
18 "artist" : ( 33, 63, stripnulls),
19 "album" : ( 63, 93, stripnulls),
20 "year" : ( 93, 97, stripnulls),
21 "comment" : ( 97, 126, stripnulls),
22 "genre" : (127, 128, ord)}
23
24 def __parse(self, filename):
25 "parse ID3v1.0 tags from MP3 file"
26 self.clear()
27 try:
28 fsock = open(filename, "rb", 0)
29 try:
30 fsock.seek(-128, 2)
31 tagdata = fsock.read(128)
32 finally:
33 fsock.close()
34 if tagdata[:3] == 'TAG':
35 for tag, (start, end, parseFunc) in self.tagDataMap.items():
36 self[tag] = parseFunc(tagdata[start:end])
37 except IOError:
38 pass
39
40 def __setitem__(self, key, item):
41 if key == "name" and item:
42 self.__parse(item)
43 FileInfo.__setitem__(self, key, item)
44
45 def listDirectory(directory, fileExtList):
46 "get list of file info objects for files of particular extensions"
47 fileList = [os.path.normcase(f) for f in os.listdir(directory)]
48 fileList = [os.path.join(directory, f) for f in fileList \
49 if os.path.splitext(f)[1] in fileExtList]
50 def getFileInfoClass(filename, module=sys.modules[FileInfo.__module__]):
51 "get file info class from filename extension"
52 subclass = "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:]
53 return hasattr(module, subclass) and getattr(module, subclass) or FileInfo
54 return [getFileInfoClass(f)(f) for f in fileList]
55
56 if __name__ == "__main__":
57 for info in listDirectory("E:\\fish", [".mp3"]):
58 print ("\n".join(["%s=%s" % (k, v) for k, v in info.items()]) )
59