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()
复制代码

转载于:https://www.cnblogs.com/apple2016/p/5367140.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值