zoukankan      html  css  js  c++  java
  • python标准库之glob介绍

     glob 文件名模式匹配,不用遍历整个目录判断每个文件是不是符合。

    1、通配符

    星号(*)匹配零个或多个字符

     1 import glob
     2 for name in glob.glob('dir/*'):
     3     print (name)
     4 
     5 dir/file.txt
     6 dir/file1.txt
     7 dir/file2.txt
     8 dir/filea.txt
     9 dir/fileb.txt
    10 dir/subdir

    列出子目录中的文件,必须在模式中包括子目录名:

     1 import glob
     2 
     3 #用子目录查询文件
     4 print ('Named explicitly:')
     5 for name in glob.glob('dir/subdir/*'):
     6     print ('	', name)
     7 #用通配符* 代替子目录名
     8 print ('Named with wildcard:')
     9 for name in glob.glob('dir/*/*'):
    10     print ('	', name)
    Named explicitly:
            dir/subdir/subfile.txt
    Named with wildcard:
            dir/subdir/subfile.txt

    2、单个字符通配符

    用问号(?)匹配任何单个的字符。

    import glob
    
    for name in glob.glob('dir/file?.txt'):
        print (name)
    
    
    dir/file1.txt
    dir/file2.txt
    dir/filea.txt
    dir/fileb.txt

    3、字符范围

    当需要匹配一个特定的字符,可以使用一个范围

    1 import glob
    2 for name in glob.glob('dir/*[0-9].*'):
    3     print (name)
    4 
    5 
    6 dir/file1.txt
    7 dir/file2.txt
  • 相关阅读:
    HDU2767 Proving Equivalences
    POJ2771 Guardian of Decency
    POJ1111 Image Perimeters
    简单就好
    工具乃思维的奴隶
    “年终奖”
    学点经济学知识(二)
    被忽略的技能
    猿类己见
    学点经济学知识(一)
  • 原文地址:https://www.cnblogs.com/shiqi17/p/12912936.html
Copyright © 2011-2022 走看看