Python下搜索文件
一个搜索文件的程序,可以选择搜索文件还是目录;也可以选择搜索模式,如果严格模式开启,只能匹配与搜索字相等的文件或者目录,如果不开启,只要一个文件或者目录存在关键词即匹配。
1 #!/usr/bin/python2
3 import os
4
5 class SearchEngine():
6 def __init__(self,path):
7 self.path=path
8
9 def search(self,word,Type=\'file\',strict=False):
10 """word:the keyword that you want to search.
11 Type:you want to search file or directory.
12 strict:if True,filename or directory name must equal to keyword;
13 if False,keyword may be a part of a filename or directory name """
14 if os.path.isdir(self.path):
15 for root,dirs,files in os.walk(self.path):
16 if Type==\'file\':
17 for filename in files:
18 if strict==False:
19 if word in filename:
20 print \'/\'.join([root,filename])
21 elif strict==True:
22 if word==os.path.splitext(filename)[0]:
23 print \'/\'.join([root,filename])
24 else:
25 print "strict:False/True"
26 elif Type==\'directory\':
27 for dirname in dirs:
28 if strict==False:
29 if word in dirname:
30 print \'/\'.join([root,dirname])
31 elif strict==True:
32 if word==dirname:
33 print \'/\'.join([root,dirname])
34 else:
35 print "strict:False/True"
36
37 else:
38 print "Type:file/directory"
39 else:
40 if Type==\'file\':
41 if strict==False:
42 if word in self.path:
43 print self.path
44 elif strict==True:
45 if word==os.path.split(self.path)[1]:
46 print self.path
47 else:
48 print "You input a filename,Not matched."
49
50 def test():
51 search=SearchEngine(\'/home/tmyyss\')
52 search.search(\'test\',\'file\',False)
53
54 if __name__==\'__main__\':
55 test()
以上是 Python下搜索文件 的全部内容, 来源链接: utcz.com/z/387398.html