A search file program, you can choose to search for files or directories, you can also select the search mode, if strict mode is turned on, can only match the search word equal to the file or directory, if not open, as long as a file or directory exists keyword that matches.
1 #!/usr/bin/python2 3 ImportOS4 5 classsearchengine ():6 def __init__(Self,path):7Self.path=Path8 9 defSearch (self,word,type='file', strict=False):Ten """word:the keyword That's want to search. One type:you want to search file or directory. A strict:if true,filename or directory name must equal to keyword; - If False,keyword is a part of a filename or directory name""" - ifOs.path.isdir (self.path): the forRoot,dirs,filesinchOs.walk (self.path): - iftype=='file': - forFileNameinchFiles: - ifstrict==False: + ifWordinchFileName: - Print '/'. Join ([root,filename]) + elifstrict==True: A ifword==os.path.splitext (filename) [0]: at Print '/'. Join ([root,filename]) - Else: - Print "strict:false/true" - eliftype=='Directory': - forDirNameinchdirs: - ifstrict==False: in ifWordinchdirname: - Print '/'. Join ([root,dirname]) to elifstrict==True: + ifword==dirname: - Print '/'. Join ([root,dirname]) the Else: * Print "strict:false/true" $ Panax Notoginseng Else: - Print "type:file/directory" the Else: + iftype=='file': A ifstrict==False: the ifWordinchSelf.path: + PrintSelf.path - elifstrict==True: $ ifWord==os.path.split (Self.path) [1]: $ PrintSelf.path - Else: - Print "You input a filename,not matched." the - defTest ():WuyiSearch=searchengine ('/home/tmyyss') theSearch.search ('Test','file', False) - Wu if __name__=='__main__': -Test ()
Search for files under Python