Python, how to list files and folders in a directory
By Flavio Copes
Learn how to list files and folders in a directory in Python using os.listdir(), then os.path.isfile() and os.path.isdir() to tell the two apart.
To list files in a directory, you can use the listdir() method that is provided by the os built-in module:
import os
dirname = '/users/Flavio/dev'
files = os.listdir(dirname)
print(files)
os.listdir() returns a list of strings, one for each entry in the directory. Files and folders are mixed together, and there is no guaranteed order. If you want them alphabetical, wrap the call in sorted().
Hidden files, the ones starting with a dot on macOS and Linux, are included too. The only entries you never get are . and ...
Getting the full paths
One thing that trips people up: listdir() returns just the names, not the paths. If the directory contains notes.txt, you get the string 'notes.txt', not '/users/Flavio/dev/notes.txt'.
Pass one of those bare names to open() and Python looks for it in the current working directory, not in the folder you listed. If you’re running the script from somewhere else, you get a FileNotFoundError for a file that clearly exists.
The fix is to join the folder path with each name, using the os.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))
os.path.join() also picks the right separator for the operating system, so the same code works on Windows.
Separating files from folders
Since listdir() gives you everything in one list, you need a second step to tell files and folders apart.
To list only the files, or only the directories, you can use os.path.isfile() and os.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))
Both functions check the actual filesystem, which is why we test the full paths and not the bare names. A bare name would be checked relative to the current working directory, and could silently report False for everything.
Note that a symbolic link pointing to a file counts as a file, and one pointing to a directory counts as a directory.
One last thing: if the directory you pass to listdir() doesn’t exist, you get a FileNotFoundError. Check first with os.path.exists(dirname) when the path comes from user input.
Related posts about python: