How to list all files in a folder using Python?

Asked

Viewed 3,291 times

1

I am building a program that needs to know the files in its work directory. So I typed the following code.

def encontrar_arq(cadena, caminho):
   encontrado = False
   # lista_arq = ls(caminho) #funcao que lista todos os arquivos do caminho
   for nome_arq in lista_arq:
       if nome_arq == cadena:
           encontrado = True
   return encontrado

1 answer

9


There are some forms, one of them is the function os.listdir:

from os import listdir

def encontrar_arq(cadena, caminho):
   encontrado = False
   lista_arq = listdir(caminho)

   for arquivo in lista_arq:
      # Use "arquivo" aqui...

To list files and directories separately, use os.walk:

from os import walk

def encontrar_arq(cadena, caminho):
   encontrado = False

   for path, diretorios, arquivos in walk(caminho):
       for arquivo in arquivos:
           # Use "arquivo" aqui...

Another alternative is the glob.glob:

from glob import glob

def encontrar_arq(cadena, caminho):
   encontrado = False

   arquivos = glob(caminho + '.*') # Para listar somente .txt altere para "*.txt"
   for arquivo in arquivos:
       # Use "arquivo" aqui...
  • Thanks @stderr, I have other problems with my code, so I haven’t been able to run your solution. That’s why the implementation I did I haven’t been able to test it yet. But just by testing the answer value.

  • @Adolfocorrea Dispo, any questions just warn!

Browser other questions tagged

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