Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1792161
  • 博文数量: 335
  • 博客积分: 4690
  • 博客等级: 上校
  • 技术积分: 4341
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-08 21:38
个人简介

无聊之人--除了技术,还是技术,你懂得

文章分类

全部博文(335)

文章存档

2016年(29)

2015年(18)

2014年(7)

2013年(86)

2012年(90)

2011年(105)

分类: Python/Ruby

2011-08-15 22:51:17

6.7. Summary

The fileinfo.py program introduced in Chapter 5 should now make perfect sense.

第五章介绍的fileinfo程序现在应该都讲得通了。

  1. """Framework for getting filetype-specific metadata.
  2.  
  3. Instantiate appropriate class with filename. Returned object acts like a
  4. dictionary, with key-value pairs for each piece of metadata.
  5.     import fileinfo
  6.     info = fileinfo.MP3FileInfo("/music/ap/mahadeva.mp3")
  7.     print "\\n".join(["%s=%s" % (k, v) for k, v in info.items()])
  8.  
  9. Or use listDirectory function to get info on all files in a directory.
  10.     for info in fileinfo.listDirectory("/music/ap/", [".mp3"]):
  11.         ...
  12.  
  13. Framework can be extended by adding classes for particular file types, e.g.
  14. HTMLFileInfo, MPGFileInfo, DOCFileInfo. Each class is completely responsible for
  15. parsing its files appropriately; see MP3FileInfo for example.
  16. """
  17. import os
  18. import sys
  19. from UserDict import UserDict
  20.  
  21. def stripnulls(data):
  22.     "strip whitespace and nulls"
  23.     return data.replace("\00", "").strip()
  24.  
  25. class FileInfo(UserDict):
  26.     "store file metadata"
  27.     def __init__(self, filename=None):
  28.         UserDict.__init__(self)
  29.         self["name"] = filename
  30.  
  31. class MP3FileInfo(FileInfo):
  32.     "store ID3v1.0 MP3 tags"
  33.     tagDataMap = {"title" : ( 3, 33, stripnulls),
  34.                   "artist" : ( 33, 63, stripnulls),
  35.                   "album" : ( 63, 93, stripnulls),
  36.                   "year" : ( 93, 97, stripnulls),
  37.                   "comment" : ( 97, 126, stripnulls),
  38.                   "genre" : (127, 128, ord)}
  39.  
  40.     def __parse(self, filename):
  41.         "parse ID3v1.0 tags from MP3 file"
  42.         self.clear()
  43.         try:
  44.             fsock = open(filename, "rb", 0)
  45.             try:
  46.                 fsock.seek(-128, 2)
  47.                 tagdata = fsock.read(128)
  48.             finally:
  49.                 fsock.close()
  50.             if tagdata[:3] == "TAG":
  51.                 for tag, (start, end, parseFunc) in self.tagDataMap.items():
  52.                     self[tag] = parseFunc(tagdata[start:end])
  53.         except IOError:
  54.             pass
  55.  
  56.     def __setitem__(self, key, item):
  57.         if key == "name" and item:
  58.             self.__parse(item)
  59.         FileInfo.__setitem__(self, key, item)
  60.  
  61. def listDirectory(directory, fileExtList):
  62.     "get list of file info objects for files of particular extensions"
  63.     fileList = [os.path.normcase(f)
  64.                 for f in os.listdir(directory)]
  65.     fileList = [os.path.join(directory, f)
  66.                for f in fileList
  67.                 if os.path.splitext(f)[1] in fileExtList]
  68.     def getFileInfoClass(filename, module=sys.modules[FileInfo.__module__]):
  69.         "get file info class from filename extension"
  70.         subclass = "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:]
  71.         return hasattr(module, subclass) and getattr(module, subclass) or FileInfo
  72.     return [getFileInfoClass(f)(f) for f in fileList]
  73.  
  74. if __name__ == "__main__":
  75.     for info in listDirectory("/music/_singles/", [".mp3"]):
  76.         print "\n".join(["%s=%s" % (k, v) for k, v in info.items()])
  77.         print

Before diving into the next chapter, make sure you're comfortable doing the following things:

在深入下一章之前,确定你已经掌握了下面的知识点:

  • Catching exceptions with try...except
  • Protecting external resources with try...finally
  • Reading from files
  • Assigning multiple values at once in a for loop
  • Using the os module for all your cross-platform file manipulation needs
  • Dynamically instantiating classes of unknown type by treating classes as objects and passing them around
  • 使用try…except捕捉异常
  • 使用try..finally保护外部资源
  • 读取文件
  • for循环一次进行多个变量赋值
  • 根据你跨平台进行操作的需要,使用os模块
  • 通过将类视作对并用它进行传值来动态的实例化一个未知类

 

阅读(947) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~