To get a list of file and directory names (folder names) in Python, use the os module function os.listdir().
os.listdir(path='.')
Returns a list containing the entry names in the directory specified by path.
os — Miscellaneous operating system interfaces — Python 3.10.0 Documentation
The os module is included in the standard library and does not need to be installed. However, “import” is required.
The following information is provided here.
- Get a list of both file and directory names.
- Get a list of file names only
- Get a list of directory names only
The following is an example of a file (directory) structure.
. └── testdir ├── dir1 ├── dir2 ├── file1 ├── file2.txt └── file3.jpg
In addition to os.listdir(), you can also use the glob module to get a list of file and directory names (folder names). glob allows you to specify conditions using wildcards (*), etc., and recursively include subdirectories.
In Python 3.4 and later, it is also possible to get a list of files and directories using the pathlib module, which can manipulate paths as objects. Like globs above, it can also be used conditionally and recursively.
Get a list of both file and directory names.
If you use os.listdir() as is, it will return a list of both file and directory names.
import os path = "./testdir" files = os.listdir(path) print(type(files)) # <class 'list'> print(files) # ['dir1', 'dir2', 'file1', 'file2.txt', 'file3.jpg']
What you get is a list of path strings.
Get a list of file names only
If you want to get a list of only file names, use the os.path.isfile() function to determine if the path is a file. passing only the file name as the argument of the os.path.isfile() function will not work, so pass the full path as shown below.os.path.isfile(os.path.join(path, f))
files = os.listdir(path) files_file = [f for f in files if os.path.isfile(os.path.join(path, f))] print(files_file) # ['file1', 'file2.txt', 'file3.jpg']
Get a list of directory names only
If you want to get a list of directory names only, use os.path.isdir() in the same way.
files = os.listdir(path) files_dir = [f for f in files if os.path.isdir(os.path.join(path, f))] print(files_dir) # ['dir1', 'dir2']