码迷,mamicode.com
首页 > 编程语言 > 详细

Python下搜索文件

时间:2015-01-09 23:42:37      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:

一个搜索文件的程序,可以选择搜索文件还是目录;也可以选择搜索模式,如果严格模式开启,只能匹配与搜索字相等的文件或者目录,如果不开启,只要一个文件或者目录存在关键词即匹配。

 1 #!/usr/bin/python
 2 
 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下搜索文件

标签:

原文地址:http://www.cnblogs.com/tmyyss/p/4214295.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!