Write a program that finds files in the current directory and all subdirectories of the current directory that contain the specified string and prints out the absolute path.
Import OS class Searchfile (object): Def __init__ (self,path= '. '): Self._path=path Self.abspath=os.pat H.abspath (self._path) # Default current directory Def findfile (self,keyword,root): filelist=[] for root,dirs,files in OS . Walk (Root): for name in Files:fitfile=filelist.append (Os.path.join root, nam e) #print (fitfile) print (Os.path.join (root, name)) #print (filelist) print
(' ...............) for I-in filelist:if os.path.isfile (i): (i) (i) (i) (i) (i) £ º
#print (i) if keyword in os.path.split (i) [1]: Print (' yes! ', i) # absolute path
#else: #print (' ... no keyword! ') def __call__ (self): while True:workpath=input (' does you want to work under the current folder? y/n: ') if (Workpath = = "): Break if Workpath== ' y ' or workpath== ' y ': Root=self.abspath # Use the current working directory as the Working directory print (' Current working directory: ', root) Dirlist=os.listdir () # Lists the files and directories under the Working directory print (dirlist) else:root =input (' Please enter the working directory: ') print (' Current working directory: ', root) keyword=input (' the keyword You are want to find: ') if (keyword== "): Break Self.findfile (keyword,root) # Lookup band specified Character file if __name__ = = ' __main__ ': search = Searchfile () search ()
Run Result:
Note: If you select Y at run time, which is the directory where the. py file is located, it is best not to put the. py file on the desktop, because it will traverse all the directories on the desktop and all the files in the directory.