Python, how to list files and folders in a directory

To list the files in a directory, you can uselistdir()Provided methodosBuilt-in modules:

import os

dirname = ‘/users/Flavio/dev’ files = os.listdir(dirname)

print(files)

To get the full path of the file, you can useos.path.join()method:

import os

dirname = ‘/users/Flavio/dev’ files = os.listdir(dirname)

temp = map(lambda name: os.path.join(dirname, name), files)

print(list(temp))

To list only files or only directories, you can useos.path.isfile()withos.path.isdir():

import os

dirname = ‘/users/Flavio/dev’ dirfiles = os.listdir(dirname)

fullpaths = map(lambda name: os.path.join(dirname, name), dirfiles)

dirs = [] files = []

for file in fullpaths: if os.path.isdir(file): dirs.append(file) if os.path.isfile(file): files.append(file)

print(list(dirs)) print(list(files))


More python tutorials: