How to do a file search using Python

Asked

Viewed 334 times

0

Problem: Implement the function search(), which accepts as input the name of a file and the path of a folder, to search for the file in the folder and in any folder contained therein, directly or indirectly. The function should return the file path if found; otherwise, none should be returned.

Like I did:

def search(file,pasta):
    import os

    for (root, dirs, files) in os.walk(path, topdown=True):
        #print(root)
        #print(dirs)
        #print(files)
        if file in files:
            print(root)


path = r"test"
file = "fileE.txt"
search(file,path)

The above program works, but the idea is to do "at hand", IE, without using os.walk, somehow recursive. Any suggestions?

  • 1

    Please correct the indentation of your code in the question. And why is the idea "do it in the hand"? Where does it say it in the problem?

  • @Woss I’d like to know how to do without using the os.walk....

1 answer

2

I’m not an expert at creating recursive functions but I did my best to answer your question. It is possible to make by hand a function like the walk through recursiveness only that I still needed to use some functions of the module os to complete this task.

Below is the function search() which scans all folders and sub-folders within the current directory looking for the desired file:

import os

def search(filename, path = os.getcwd()):

    results = os.listdir(path)

    # Verifica se há um arquivo dentro do diretório atual.
    if filename in results:
        yield path

    for found in results:

        # Junta o caminho atual com o nome do arquivo ou diretório achado.
        found = os.path.join(path, found)

        # Verifica se é um diretório. Se ele for, a função "search" 
        # será chamada novamente para fazer uma busca nesta pasta encontrada
        # e depois será retornado através do yield todos os diretórios 
        # possuem o arquivo desejado.

        if os.path.isdir(found):
            for path in search(filename, found):
                if path: yield path

Note in the above code that instead of using return I used the yield. I did it so that the function can continue the execution of for loop and go checking the following directories at the same time that returns the obtained path.

Maybe there’s a much better way than mine to create that function, but that’s the best I could think of and create. I hope I’ve helped you.

  • @eanExtreme002 Why Yield ?

  • I explained in the reply. I used the yield to return the paths without the program finishing the execution of the for loop.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.