zoukankan      html  css  js  c++  java
  • Python下搜索文件

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

     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()
  • 相关阅读:
    Kafka——相关概念及核心配置说明
    Kafak——Kafka-Manager安装部署
    Kafka——集群安裝部署(自带Zookeeper)
    ElasticSearch日志删除命令
    QML ListView json
    Qt websocket
    Tickets
    3.docker容器的数据卷
    2.docker命令
    1.安装和初始化docker
  • 原文地址:https://www.cnblogs.com/tmyyss/p/4214295.html
Copyright © 2011-2022 走看看