3.3 查找文件
3.3.1 使用fnmatch找到特定的文件
fnmatch主要作用是文件名称的匹配,并且匹配的模式使用的unix shell风格。
例如:
#!/usr/bin/python3
import os
import fnmatch
for filename in os.listdir('.'):
if fnmatch.fnmatch(filename,'*.conf'): #匹配模式为星号,表示任意的字符
print(filename)
输出为:
root@liu-ubuntu:~# ./08-fnmatch.py
test.conf
fnmatch.fnmatch是一个布尔函数,返回为True或者Faulse。
主要使用的匹配模式如下:
if fnmatch.fnmatch('kel','?el'): #匹配模式为问号,及匹配一个任意字符
print('match')
if fnmatch.fnmatch('kel','[a-z]el'): #匹配模式为单个字符,在a-z之间
print('match')
if fnmatch.fnmatch('1el','[!a-z]el'):#匹配模式为不能是a-z之间的字符
print('match')
3.3.2 使用glob找到特定的文件
glob是Python自己带的一个文件操作相关模块,用它可以查找符合自己目的的文件,类似于Windows下的文件搜索,支持通配符操作*,?,[]
这三个通配符,*代表0个或多个字符,?代表一个字符,[]匹配指定范围内的字符,如[0-9]匹配数字。
glob模块的主要方法就是glob,返回所有匹配的文件路径列表。它只有一个参数pathname,定义了文件路径匹配规则,这里可以是绝对路径,也可以是相对路径。
例如:
#!/usr/bin/python3
import glob
print(glob.glob('./??-*.py'))
结果为:
root@liu-ubuntu:~# ./09-glob.py
['./08-fnmatch.py', './01-argv.py', './09-glob.py', './05-configparser.py', './04-getpass.py', './07-log.py', './02-stdinout.py', './06-argparse.py', './03-sysexit.py']
3.3.3 使用os.walk遍历目录树
os.walk的声明为:
os.walk(top, topdown=True, onerror=None, followlinks=False)
执行可以得到一个三元tuple(dirpath, dirnames, filenames),
第一个为起始路径,第二个为起始路径下的文件夹,第三个是起始路径下的文件。
dirpath 是一个string,代表目录的路径,
dirnames 是一个list,包含了dirpath下所有子目录的名字。
filenames 是一个list,包含了非目录文件的名字。
这些名字不包含路径信息,如果需要得到全路径,需要使用os.path.join(dirpath, name)。
通过for循环自动完成递归枚举
例如有树形结构如下:
root@liu-ubuntu:~# tree
.
├── 01-argv.py
├── 02-stdinout.py
├── 03-sysexit.py
├── 04-getpass.py
├── 05-configparser.py
├── 06-argparse.py
├── 07-log.py
├── 08-fnmatch.py
├── 09-glob.py
├── example
│ ├── __init__.py
│ ├── items.py
│ ├── pipelines.py
│ ├── settings.py
│ └── spiders
│ ├── dmoz.py
│ ├── __init__.py
│ ├── mycrawler_redis.py
│ └── myspider_redis.py
├── test.conf
└── test.py
编写程序如下:
#!/usr/bin/python3
import os
for root, dirs, files in os.walk('.'):
for dir in dirs:
print(os.path.join(root, dir))
for file in files:
print(os.path.join(root, file))
执行结果为:
root@liu-ubuntu:~# ./10-walk.py
./example
./08-fnmatch.py
./test.py
./10-walk.py
./01-argv.py
./09-glob.py
./05-configparser.py
./test.conf
./04-getpass.py
./07-log.py
./02-stdinout.py
./06-argparse.py
./03-sysexit.py
./example/spiders
./example/items.py
./example/settings.py
./example/__init__.py
./example/pipelines.py
./example/spiders/mycrawler_redis.py
./example/spiders/dmoz.py
./example/spiders/__init__.py
./example/spiders/myspider_redis.py