Get a List of File and Directory Names in Python
In Python, the os.listdir()
function allows you to get a list of file and directory (folder) names within a specific directory.
In addition to os.listdir()
, you can also use the glob
module to retrieve file and directory names. The glob
module offers more flexibility, letting you specify conditions with wildcards like *
, and supporting recursive extraction, including subdirectories.
The following files and directories are used as examples.
temp/
├── dir1/
│ └── file_in_dir
├── dir2/
├── file1
├── file2.txt
└── file3.jpg
Get a list of both file and directory names: os.listdir()
When you specify the directory path (as a path string or a path-like object such as pathlib.Path
) in os.listdir()
, it returns a list of file and directory names within the specified directory.
Note that the trailing separator (/
) of the directory can be either included or omitted when specifying with a path string.
import os
dir_path = "temp"
files = os.listdir(dir_path)
print(files)
# ['file2.txt', 'dir2', 'file3.jpg', 'file1', 'dir1']
print(type(files))
# <class 'list'>
If the argument is omitted, os.listdir()
returns a list of file and directory names in the current directory.
Files and directories in subdirectories are not included. Use the glob
module to get the list recursively.
The list is in arbitrary order. Use sorted()
or sort()
if you want to sort.
print(sorted(files))
# ['dir1', 'dir2', 'file1', 'file2.txt', 'file3.jpg']
For information on how to filter a list of strings based on specific conditions (e.g., extracting only names containing particular strings), refer to the following article.
Get a list of only file names
To get a list of only file names, use os.path.isfile()
in a list comprehension to check if the path is a file. Since passing just the filename to os.path.isfile()
doesn't work, join it with the directory name using os.path.join()
.
- List comprehensions in Python
- Check if a file or a directory exists in Python
- Get the filename, directory, extension from a path string in Python
import os
dir_path = "temp"
files_file = [
f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))
]
print(files_file)
# ['file2.txt', 'file3.jpg', 'file1']
Get a list of only directory names
The concept for getting a list of only directory names is the same as for files in the previous section. Use os.path.isdir()
to check if the path is a directory.
import os
dir_path = "temp"
files_dir = [
f for f in os.listdir(dir_path) if os.path.isdir(os.path.join(dir_path, f))
]
print(files_dir)
# ['dir2', 'dir1']