The os.listdir()
method in Python is used to list all the entries (files and directories) in a specified directory. It provides a way to interact with the file system and retrieve the contents of a directory.
1. Syntax
os.listdir(path='.')
path
is the directory path you want to list. If not specified, it defaults to the current working directory (denoted by '.'
).
2. Importing the os
Module
To use the os.listdir()
method, you need to import the os
module:
import os
3. Example Usage
Here are some examples demonstrating how to use os.listdir()
:
3.1 List Files and Directories in the Current Directory
import os
# List all files and directories in the current directory
entries = os.listdir('.')
print(entries)
3.2 List Files and Directories in a Specific Directory
import os
# List all files and directories in a specific directory
directory_path = '/path/to/directory'
entries = os.listdir(directory_path)
print(entries)
3.3 Handle Non-Existent Directory
If the directory does not exist, os.listdir()
raises a FileNotFoundError
:
import os
try:
entries = os.listdir('/nonexistent/directory')
except FileNotFoundError as e:
print(e)
4. Filtering Entries
You can filter the entries to only list files or directories using additional code:
4.1 List Only Files
import os
directory_path = '/path/to/directory'
entries = os.listdir(directory_path)
# Filter out directories
files = [f for f in entries if os.path.isfile(os.path.join(directory_path, f))]
print(files)
4.2 List Only Directories
import os
directory_path = '/path/to/directory'
entries = os.listdir(directory_path)
# Filter out files
directories = [d for d in entries if os.path.isdir(os.path.join(directory_path, d))]
print(directories)
5. Summary
The os.listdir()
method is a useful function for listing the contents of a directory. By specifying the path, you can get the names of all files and directories within it. Additional processing can filter the results to meet specific needs, such as separating files and directories.