Find file using Python

Asked

Viewed 3,022 times

0

I have a question, how to locate a file using python. The goal is to locate a file inside a directory and return all the way from the directory where the file is and if you do not find the file, return None. I created the code below, but it returns all the directories that do not contain the file and also the directory that contains the file. Can anyone check if it is correct or forgot something? Thanks!

import os

diret = "/"
filename = "teste"

def achar_arq():

for roots, dirs, files in os.walk(diret):

    if filename in files:
        print(os.path.join(roots,filename))
    if filename not in files:
        print('None')

print(achar_arq())
  • Does the search need to be recursive in all child directories? If yes, what should happen if more than one file with the same name is found?

  • It must return all the directories that contain a file with this same name, but only these, that is, either return the directories that have the file or return only one None.

1 answer

1


As of Python version 3.4 there are no more justifications¹ to use the library os to manipulate directories and files, since in this version the library was added pathlib, that abstracts the functions of os in a much simpler API to use.

To create an object that represents a directory just do:

diretorio = pathlib.Path('diretorio')

And to fetch all files with the name teste inside this directory just do:

arquivos = diretorio.glob('**/teste')

The ** indicates that the file may be at any subdirectory level, not just at the root.

For a directory structure similar to:

└ diretorio/
.   └ arquivos/
.   .   └ arquivos/
.   .   .   └ banana
.   .   .   └ teste
.   .   └ teste
.   └ teste

Just do:

diretorio = pathlib.Path('diretorio')
arquivos = diretorio.glob('**/teste')

for arquivo in arquivos:
    print(arquivo)

The exit would be:

arquivos/teste
arquivos/arquivos/teste
arquivos/arquivos/arquivos/teste

It is worth mentioning that the return of glob will be an eternal object of instances of pathlib.PosixPath, if you want to search how to manipulate such objects.

1) There is, but in the vast majority of cases the library pathlib can be used

  • Thank you. But a doubt, if my version is not that, the answer I provided would have the error where?

Browser other questions tagged

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