需求
写脚本需要便利某一目录下所有的图片文件进行处理
之前一直用os.listdir()配合列表推导式,不够简洁
最近学到了可以调用内置glob模块
用法
glob支持有限的正则表达式,常用通配符有三个:
- "*"匹配0个或多个字符;
- "?"匹配单个字符;
- "[]"匹配指定范围内的字符,如:[0-9]匹配数字。
举例
>>> import glob
>>> glob.glob('/Users/azure/Downloads/*.jpg')
['/Users/azure/Downloads/1591765004_337094.jpg', '/Users/azure/Downloads/1591764904_687304.jpg', '/Users/azure/Downloads/1591764899_493866.jpg', '/Users/azure/Downloads/1591764993_846651.jpg', '/Users/azure/Downloads/v2-d9c4356f97fdb3f45e96768dab7f6706_r.jpg', '/Users/azure/Downloads/1591765005_377286.jpg', '/Users/azure/Downloads/1591764907_704452.jpg', '/Users/azure/Downloads/1591765016_281432.jpg', '/Users/azure/Downloads/1591764921_840422.jpg', '/Users/azure/Downloads/1591764988_783247.jpg', '/Users/azure/Downloads/1591764930_133601.jpg', '/Users/azure/Downloads/1591764915_923076.jpg', '/Users/azure/Downloads/1591764926_403385.jpg', '/Users/azure/Downloads/1591764918_716200.jpg', '/Users/azure/Downloads/c98de2fa2005189f2dad71b1c83a11e6.jpg']
>>>
注意,路径不支持~替代home
>>> glob.glob('~/Downloads/*.jpg')
[]