##language:zh ''' 目录处理 ''' * 目录,就象 规则文件,也非常容易处理,我们先来侦听目录: {{{#!python import os for fileName in os.listdir ( '/' ): print fileName }}} * 正如所见,非常的简单 仅仅三行内就解决问题 * 创建目录也一样简单:{{{#!python import os os.mkdir ( 'testDirectory' ) }}} * 删除和建立目录一样简单:{{{#!python import os os.rmdir ( 'testDirectory' ) }}} * 可以一次性创建很多目录:{{{#!python import os os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' ) }}} * 不用任何多余操作,一次性清除很多目录也一样方便:{{{#!python import os os.removedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' ) }}} * 如果我们霰针对不同类型的文件进行操作,那未有"fnmatch"模块可以轻易的进行处理. * 这里,我们将所有遇到的 ".txt" 文件内容打印出来,所有 ".exe" 文件的名称打印出来:{{{#!python import fnmatch import os for fileName in os.listdir ( '/' ): if fnmatch.fnmath ( fileName, '*.txt' ): print open ( fileName ).read() elif fnmatch.fnmatch ( fileName, '*.exe' ): print fileName }}} * 其中 '''*''',星号代表可以匹配所有字符(当然是正则表达式中意义) * 自然的,我们想仅仅匹配一个字符就 '''?''' -- 问号: {{{#!python import fnmatch import os for fileName in os.listdir ( '/' ): if fnmatch.fnmatch ( fileName, '?.txt' ): print 'Text file.' }}} * 在"fnmatch"模块,我们可以创建正则表达式来应用,只要通过 "re" 模块: {{{#!python import fnmatch import os import re filePattern = fnmatch.translate ( '*.txt' ) for fileName in os.listdir ( '/' ): if re.match ( filePattern, fileName ): print 'Text file.' }}} * 如果想搜索一种类型的所有文件,有"glob"模块轻易的作到,使用模式与 "fnmatch" 模块一样: {{{#!python import glob for fileName in glob.glob ( '*.txt' ): print 'Text file.' }}} * 也可以在正则表达式的模式中指定一定范围内的特性, 比如说这样我们可以搜索出所有文件名是一个数字的 文本文件: {{{#!python import glob for fileName in glob.glob ( '[0-9].txt' ): print fileName }}} ---- -- ZoomQuiet [<>]