The Python lookup file name contains the specified string __python

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.