I build a program that requires to know the files in the working directory ( current working directory ). Therefore, I made the following code, which finds and confirms the existence of the file named 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 in a folder in a Python list?
There are different ways to get all the files in a directory. Different ways are shown below, all of them return a list when called like this:
Greater efficiency with
os.scandir()
- python-3.5Returns an iterator to objects that hold the properties of files, making it more efficient (for example, you don't need to make an additional system call to see if an object is a file or a directory).
Or if you want to get the absolute path of each file:
With the library
pathlib
and its main classPath
- python-3.4It offers a higher level of consistency between different operating systems, without the need to directly reference
os
, also avoiding many system calls.* thanks to kikocorreoso for the reference and his jewelery article .
List all directories and files with
listdir()
- python-2.x and python-3.xOr just files :
More control with
os.walk()
- python-2.2 and python-3.xYou can get only the files in a more compact way :
Or you can have more control if you want, getting two lists ( directories and files )
And if you also want to get the files from all the subdirectories , let's iterate as follows:
Using wildcards in
glob()
- python-2.x and python-3.xTo search for files using wildcards (
*
,?
,[seq]
and[!seq]
)This function returns the full path of each file.
Example:
Find files with a regular expression - python-2.2 and python-3.x
Example:
Hope this can help you :)