glob模块--查询一个文件名列表

复制代码
'''python中,glob模块是用来查找匹配的文件的
    在查找的条件中,需要用到Unix shell中的匹配规则:

       *    :   匹配所所有
       ?    :   匹配一个字符
       *.*  :   匹配如:[hello.txt,cat.xls,xxx234s.doc]
       ?.*  :   匹配如:[1.txt,h.py]
       ?.gif:   匹配如:[x.gif,2.gif]
    可以参考:fnmatch
    如果没有匹配的,glob.glob(path)将返回一个空的list:[]
'''
复制代码

以下是我的demo

运行效果:

=============================================

代码部分:

=============================================

复制代码
 1 #python glob
 2 
 3 '''
 4     在python中,glob模块是用来查找匹配的文件的
 5     在查找的条件中,需要用到Unix shell中的匹配规则:
 6 
 7        *    :   匹配所所有
 8        ?    :   匹配一个字符
 9        *.*  :   匹配如:[hello.txt,cat.xls,xxx234s.doc]
10        ?.*  :   匹配如:[1.txt,h.py]
11        ?.gif:   匹配如:[x.gif,2.gif]
12 
13     如果没有匹配的,glob.glob(path)将返回一个空的list:[]
14 '''
15 import glob
16 
17 def get_all():
18     '''获取目录[c:\\tmp]下面所有的文件'''
19     return glob.glob('c:\\tmp\\*.*')
20 
21 def get_my_file():
22     '''获取目录[c:\\tmp]下面文件名为4个字符的文件'''
23     return glob.glob('c:\\tmp\\????.txt')
24 
25 def get_batch_file():
26     '''获取目录[c:\\tmp]下面扩展名为\'.txt\'的文件'''
27     return glob.glob('c:\\tmp\\*.txt')
28 
29 def main():
30     print('获取目录[c:\\tmp]下面所有的文件:')
31     tem_files = get_all()
32     print(tem_files)
33     print('获取目录[c:\\tmp]下面文件名为4个字符的文件:')
34     tem_files = get_my_file()
35     print(tem_files)
36     print('获取目录[c:\\tmp]下面扩展名为\'.txt\'的文件:')
37     tem_files = get_batch_file()
38     print(tem_files)
39 
40 if __name__ == '__main__':
41     main()
复制代码
posted @ 2016-04-08 10:58  垄上行  阅读(1626)  评论(0编辑  收藏  举报