Python: How To Find A File In Python-Search For A File In Python-DecodingDevOps

How To Find A File In Python-Search For A File-DecodingDevOps

Sometimes remembering precisely where you stored a file can be difficult. An advanced search gives you the option to find files or folders by type, name, etc. This article provides a file searching utility, created by using the power of the most versatile programming language called python.

Step-1:

importing libraries necessary for find a file in python

import os

Using os module we can interact with operating system. With os module we can create and delete the directories, we can fetch the files and content in that directories.

Step-2:

Define a function and search for the file in python

Using the following loops and os.walk() function generates the file names in a directory tree by walking the tree either top-down or bottom.up.

def find(file_name):                             #function name find is created

             count=0                                   # initialise the count to zero

             for root,dir,files in os.walk('c:\\'):    #using for loop and os.walk() function as dicussed above

                if file_name in files:                 #using if loop to check whether the file name is in files

                     print(root,file_name)             #prints root and file name

                     count=count+1                     #adds 1 to counter and starts the loop with count=1

             print("we found"+count+'results')         #if one file is found it prints we found 1 result

             print("finish")                           #prints finish

             input()

     try:                                              # using the try block

        s=input("enter name of file")                  # giving the input file name

        find(s)                                        # after giving the file name return to the find function

     except:                                           # using the except block

        print("error")

it prints error if the file is not found.

 

  • How To Find A File In Python-Search For A File
  • how to find a file in python

Leave a Reply

Your email address will not be published. Required fields are marked *