目录处理

  • 目录,就象 规则文件,也非常容易处理,我们先来侦听目录:

       1 
       2     import os
       3     for fileName in os.listdir ( '/' ):
       4        print fileName
    
    • 正如所见,非常的简单 仅仅三行内就解决问题
  • 创建目录也一样简单:

       1     import os
       2     os.mkdir ( 'testDirectory' )
    
  • 删除和建立目录一样简单:

       1     import os
       2     os.rmdir ( 'testDirectory' )
    
  • 可以一次性创建很多目录:

       1     import os
       2     os.makedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )
    
  • 不用任何多余操作,一次性清除很多目录也一样方便:

       1     import os
       2     os.removedirs ( 'I/will/show/you/how/deep/the/rabbit/hole/goes' )
    
  • 如果我们霰针对不同类型的文件进行操作,那未有"fnmatch"模块可以轻易的进行处理.
    • 这里,我们将所有遇到的 ".txt" 文件内容打印出来,所有 ".exe" 文件的名称打印出来:

         1     import fnmatch
         2     import os
         3 
         4     for fileName in os.listdir ( '/' ):
         5 
         6        if fnmatch.fnmath ( fileName, '*.txt' ):
         7 
         8           print open ( fileName ).read()
         9 
        10        elif fnmatch.fnmatch ( fileName, '*.exe' ):
        11 
        12           print fileName
      
    • 其中 *,星号代表可以匹配所有字符(当然是正则表达式中意义)

    • 自然的,我们想仅仅匹配一个字符就 ? -- 问号:

         1     import fnmatch
         2 
         3     import os
         4 
         5     for fileName in os.listdir ( '/' ):
         6 
         7        if fnmatch.fnmatch ( fileName, '?.txt' ):
         8 
         9           print 'Text file.'
      
    • 在"fnmatch"模块,我们可以创建正则表达式来应用,只要通过 "re" 模块:
         1 
         2     import fnmatch
         3 
         4     import os
         5 
         6     import re
         7 
         8     filePattern = fnmatch.translate ( '*.txt' )
         9 
        10     for fileName in os.listdir ( '/' ):
        11 
        12        if re.match ( filePattern, fileName ):
        13 
        14           print 'Text file.'
      
    • 如果想搜索一种类型的所有文件,有"glob"模块轻易的作到,使用模式与 "fnmatch" 模块一样:
      •    1     import glob
           2 
           3     for fileName in glob.glob ( '*.txt' ):
           4 
           5        print 'Text file.'
        
    • 也可以在正则表达式的模式中指定一定范围内的特性, 比如说这样我们可以搜索出所有文件名是一个数字的 文本文件:
         1     import glob
         2 
         3     for fileName in glob.glob ( '[0-9].txt' ):
         4 
         5        print fileName
      


-- ZoomQuiet [2005-02-06 14:59:24]