How to list all files in a folder using Python?

I build a program that requires knowing the files of the working directory (current working directory ). Therefore, I made the following code, which searches for and confirms the existence of the name file arq_buscado:

def encontrar_arq(arq_buscado, camino):
   encontrado = False
   # lista_arq = ls(camino) #función que lista todos los archivos de la ruta
   for nome_arq in lista_arq:
       if nome_arq == arq_buscado:
           encontrado = True
   return encontrado

How can I get the list of all files from a a folder in a Python List?

 8
Author: Mariano, 2016-09-19

2 answers

There are different ways to get all files from a directory. Below are different ways, all of them return a list by calling them like this:

lista_arq = ls(ruta)   # no especificar ruta para tomar el directorio actual


  1. Higher efficiency with os.scandir() - python-3.5

    Returns a iterator to objects that maintain file properties, making it more efficient (for example, you don't need to make a system call to see if an object is a file or a directory).

    from os import scandir, getcwd
    
    def ls(ruta = getcwd()):
        return [arch.name for arch in scandir(ruta) if arch.is_file()]
    

    Or if you want to get the absolute path of each file:

    from os import scandir, getcwd
    from os.path import abspath
    
    def ls(ruta = getcwd()):
        return [abspath(arch.path) for arch in scandir(ruta) if arch.is_file()]
    


  1. With the Library pathlib and its main classPath - python-3.4

    Provides higher level of consistency between different operating systems, without the need to reference directly to os, avoiding also many calls to the system.

    from pathlib import Path
    
    def ls(ruta = Path.cwd()):
        return [arch.name for arch in Path(ruta).iterdir() if arch.is_file()]
    

    * thanks to kikocorreoso for the reference and your article of joyitas.


  1. List all directories and files with listdir() - python-2.x y python-3.x

    from os import listdir
    
    def ls(ruta = '.'):
        return listdir(ruta)
    

    Or just files :

    from os import listdir
    from os.path import isfile, join
    
    def ls(ruta = '.'):
        return [arch for arch in listdir(ruta) if isfile(join(ruta, arch))]
    


  1. Greater control with os.walk() - python-2.2 and python-3.x

    You can get only files more compactly :

    from os import walk
    
    def ls(ruta = '.'):
        return next(walk(ruta))[2]
    

    Or you can have more control if you want, getting two lists ( directories and files )

    from os import walk
    
    def ls(ruta = '.'):
        dir, subdirs, archivos = next(walk(ruta))
        print("Actual: ", dir)
        print("Subdirectorios: ", subdirs)
        print("Archivos: ", archivos)
        return archivos
    

    And if you also want to get files from all subdirectories, you can iterate as follows:

    from os import walk, getcwd
    
    def ls(ruta = getcwd()):
        listaarchivos = []
        for (_, _, archivos) in walk(ruta):
            listaarchivos.extend(archivos)
        return listaarchivos
    


  1. Using wildcards in glob() - python-2.x y python-3.x

    To search for files using wildcards (*, ?, [seq] and [!seq])

    from glob import glob
    
    def ls(expr = '*.*'):
        return glob(expr)
    

    This function returns the full path of each file.

    Example:

    print(ls('/etc/*.conf'))
    


  1. Find files with a regular expression - python-2.2 y python-3.x

    from os import walk, getcwd, path
    import re
    
    def ls(regex = '', ruta = getcwd()):
        pat = re.compile(regex, re.I)
        resultado = []
        for (dir, _, archivos) in walk(ruta):
            resultado.extend([ path.join(dir,arch) for arch in 
                                  filter(pat.search, archivos) ])
            # break  # habilitar si no se busca en subdirectorios
        return resultado
    

    Example:

    print(ls( r'-\d+\.[^.\d]*$', '/'))
    
 24
Author: Mariano, 2017-08-04 19:21:22
import os
def encontrar_arq(arq_buscado, camino):
    encontrado = False
    for i in camino:
        if camino == arq_buscando:
            econtrado = True
    return encontrado

I hope it serves you:)

 2
Author: binario_newbie, 2018-03-26 23:23:51