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?
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
-
Higher efficiency with
os.scandir()
- python-3.5Returns 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()]
-
With the Library
pathlib
and its main classPath
- python-3.4Provides 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.
-
List all directories and files with
listdir()
- python-2.x y python-3.xfrom 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))]
-
Greater control with
os.walk()
- python-2.2 and python-3.xYou 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
-
Using wildcards in
glob()
- python-2.x y python-3.xTo 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'))
-
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]*$', '/'))
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:)