I'd like to know how to use the library os
to list files from a given directory .
I'd like to know how to use the library os
to list files from a given directory .
os.listdir
. You pass a path (relative or absolute) and it gives you the names of all the files, folders and links contained in it. Then you can filter by file if you want (using os.path.isfile
), or by other criteria:
import os
caminhos = [os.path.join(pasta, nome) for nome in os.listdir(pasta)]
arquivos = [arq for arq in caminhos if os.path.isfile(arq)]
jpgs = [arq for arq in arquivos if arq.lower().endswith(".jpg")]
Note: If you are using Python 2, and passing a common string (not a unicode
), the results will come as common strings, which can cause problems if there are files with accents in the name. It is therefore recommended to use Unicode in all operations, explicitly converting to unicode
if you are in doubt about the type.
You can use os.walk , it returns a tuple with the path , directory, file, as you are only interested in the file, you can skip the first two parts by doing:
for _, _, arquivo in os.walk('/home/user'):
print(arquivo)
Hello. The package offers a range of possibilities.
recursive path + file
import os
def files_path04(path):
for p, _, files in os.walk(os.path.abspath(path)):
file in files:
print(os.path.join(p, file)))
files_path04('/tmp')
An example for multiple directories:
def files_path05(*args):
for item in args:
for p, _, files in os.walk(os.path.abspath(item)):
for file in files:
print(os.path.join(p, file))
files_path05('/home', '/tmp')
You can still set a return with a string list, containing the file or a tuple separating the path and file.
def files_path06(*args):
l = []
for item in args:
for p, _, files in os.walk(os.path.abspath(item)):
for file in files:
l.append((p, file))
return l
files_path06('/home', '/tmp')
Listing through list of understanding
def files_path09(path):
'''return list of tuple(path, file)'''
return [(p, file) for p, _, files in os.walk(os.path.abspath(path)) for file in files]
def files_path10(path):
'''return list of string'''
return [os.path.join(p, file) for p, _, files in os.walk(os.path.abspath(path)) for file in files]