实现方式一:
使用pyhon的os模块,借助os.listdir();os.pah.isfile();os.path.isdir();os.path.join()等操作文件和目录的方法
思路:
从上往下,层层搜索,每一次迭代判断文件类型作为分叉点,
难点在于遇到逐层这里,用到了“递归”查询的概念
#!/usr/bin/python # -*- coding:utf8 -*- import os import os.path def search(path,key): for i in os.listdir(path): if os.path.isfile(os.path.join(path,i)) and key in i: print os.path.join(path,i) if os.path.isdir(os.path.join(path,i)): search(os.path.join(path,i),key) pathword = raw_input(‘Enter path> ‘) keyword = raw_input(‘Enter key> ‘) search(pathword,keyword)
实现方式二:
使用os模块的walk方法
walk(top, topdown=True, onerror=None, followlinks=False)
Directory tree generator. 目录树的生成器,类似于tree命令,多次迭代实现
dirpath(字串), dirnames(列表), filenames(列表) -->元组
#!/usr/bin/python # -*- coding:utf8 -*- import os import os.path def search(path,key): for i in os.walk(path): for j in i[2]: if key in j: print os.path.join(i[0],j) pathword = raw_input(‘Enter path> ‘) keyword = raw_input(‘Enter key> ‘) search(pathword,keyword)
执行结果:
[root@docker01 tmp]# python search2.py Enter path> /etc 路径 Enter key> pass 关键词 /etc/passwd- /etc/passwd /etc/pam.d/password-auth-ac /etc/pam.d/password-auth /etc/pam.d/passwd /etc/selinux/targeted/modules/active/modules/passenger.pp /etc/security/opasswd
题目参考于廖老师的python教程:
本文出自 “Zcy.gy” 博客,请务必保留此出处http://1064187464.blog.51cto.com/9108437/1775060
原文地址:http://1064187464.blog.51cto.com/9108437/1775060