os.listdir
Get the names of the files and directories inside a directory.
Python 3.13
os.listdir(path='.')Parameters
- pathstr | PathLikeoptional
- The path to the directory; the current one by default.
Return value
A list of names without the directory path; the order is not guaranteed.
Examples
Files in a directory
Python 3.13
import os
os.makedirs('demo', exist_ok=True)
for name in ['b.txt', 'a.txt']:
open(os.path.join('demo', name), 'w').close()
print(sorted(os.listdir('demo')))['a.txt', 'b.txt']
Only files with the .txt extension
Python 3.13
import os
os.makedirs('data', exist_ok=True)
for name in ['report.txt', 'photo.png', 'notes.txt']:
open(os.path.join('data', name), 'w').close()
print(sorted(name for name in os.listdir('data') if name.endswith('.txt')))['notes.txt', 'report.txt']
Details
The special entries . and .. are not included. Raises FileNotFoundError if the directory does not exist.
