* 作者:煮酒品茶 tea
* 博客:http://www.zwhset.com http://cwtea.blog.51cto.com
* 目前在京峰教育担任python讲师
#0、GLOB 文件通配符 模块介绍
**glob(pathname) 方法**
> 返回匹配pathname的一个列表,pathname中包含 shell常用的* ?号元字符
> \* 匹配多个字符
> ? 区配1个字符
> exp: **/\*/\*.gif ** **./[0-9].***
**iglob(pathname)**
> 返回匹配pathname的一个生成器对象,与glob的关系就像是列表解析与生成器的关系
#1、glob.glob 返回列表对象
~~~
In [3]: glob.glob('/etc/*.conf') # 匹配etc下所有conf
Out[3]:
['/etc/cgconfig.conf',
'/etc/sestatus.conf',
'/etc/GeoIP.conf',
...
]
In [4]: glob.glob('/etc/r*.conf') #匹配etc下r开头的所有conf
Out[4]:
['/etc/request-key.conf',
'/etc/redis.conf',
'/etc/resolv.conf',
'/etc/rsyslog.conf']
In [5]: glob.glob('/etc/?e*.conf') #使用?号匹配单个字符
Out[5]:
['/etc/sestatus.conf',
'/etc/GeoIP.conf',
'/etc/request-key.conf',
'/etc/redis.conf',
'/etc/resolv.conf']
~~~
#2、glob.iglob 反正生成器对象
~~~
In [7]: files = glob.iglob('/etc/*.conf')
In [8]: next(files)
Out[8]: '/etc/cgconfig.conf'
In [9]: next(files)
Out[9]: '/etc/sestatus.conf'
In [10]: next(files)
Out[10]: '/etc/GeoIP.conf'
~~~
#3、实际场景
> 我们知道,一般匹配会有字符串的方法匹配、正则匹配、如果需要选择匹配文件名可以通过glob的方法来进行匹配。
> 配合一些其它模块可以去批量打开很多文件。
匹配安装包:
~~~
In [28]: glob.glob('/root/tools/*-[0-9].[0-9].[0-9].*')
Out[28]: ['/root/tools/Python-2.7.6.tgz']
~~~
这个代码看起来有点傻,因为他并不是正则,所以支持还是比较少的。
- python核心
- python27编译安装
- 原处修改以及拷贝
- loop
- 内置的变量
- 内置类型
- python内置方法
- 内置方法列表
- 求绝对值-abs
- 求商取余-divmod
- 交换输入-input
- [未完]文件打开函数-open
- staticmethod
- 判断迭代对象真假all
- 判断迭代对象真假any
- 枚举对象enumerate
- 整数转换类型int
- ascii码转换ord-chr-unichr
- 类型转换str
- python执行字符串表达式eval
- 类型判断isinstance
- 数学计算pow
- 数学计算和sum
- 不可变集合frozenset
- zip
- 比较cmp
- basestring类型判断
- 反转序列迭代器resversed
- python模块
- glob
- sys.argvgetopt-argparse
- os
- sys
- requests
- random
- time
- date
- zlib-gzip-bz2-zipfile-tarfile
- ftp
- paramiko
- pexpect
- 数据库模块
- redis
- mysql
- mongodb
- __builtin__
- 学生PYTHON分享
- 学生运维分享