glob

python3 glob模块
python官网解释

  • glob模块根据Unix shell使用的规则查找与指定模式匹配的所有路径名,尽管结果以任意顺序返回。用它可以查找符合特定规则的文件路径名
  • 查找文件只用到三个匹配符:"*", “?”, “[]”。
    • “*” 匹配0个或多个字符
    • “?” 匹配单个字符
    • “[]” 匹配指定范围内的字符
    • 如果没有匹配的,glob.glob(path)将返回一个空的列表[]
  • 包括
    • glob.glob(pathname, *, recursive=False)
    • glob.iglob(pathname, recursive=False)
    • glob.escape(pathname)
  • glob.glob()示例
  1. glob.py
import glob
def get_all():
    '''获取目录'D:/spyder_project/exercise'下面所有的文件'''
    return glob.glob('D:/spyder_project/exercise/*')

def get_my_file():
    '''获取目录'D:/spyder_project/exercise'下面文件名为4个字符的文件'''
    return glob.glob('D:/spyder_project/exercise/????.txt')

def get_batch_file():
    '''获取目录'D:/spyder_project/exercise'下面扩展名为'.txt'的文件'''
    return glob.glob('D:/spyder_project/exercise/*.txt')

def main():
    print('获取目录D:/spyder_project/exercise下面所有的文件:')
    tem_files = get_all()
    print(tem_files)
    print('获取目录D:/spyder_project/exercise下面文件名为4个字符的文件:')
    tem_files = get_my_file()
    print(tem_files)
    print('获取目录D:/spyder_project/exercise下面扩展名为.txt的文件:')
    tem_files = get_batch_file()
    print(tem_files)

if __name__ == '__main__':
    main()
  1. 目录D:/spyder_project/exercise文件如下
    在这里插入图片描述
  2. 结果
获取目录D:/spyder_project/exercise下面所有的文件:
['D:/spyder_project/exercise\\a.png.jpg', 'D:/spyder_project/exercise\\b.txt.txt', 'D:/spyder_project/exercise\\cccc.txt.txt', 'D:/spyder_project/exercise\\yq.doc.doc']
获取目录D:/spyder_project/exercise下面文件名为4个字符的文件:
[]
获取目录D:/spyder_project/exercise下面扩展名为.txt的文件:
['D:/spyder_project/exercise\\b.txt.txt', 'D:/spyder_project/exercise\\cccc.txt.txt']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值