Appearance
How to list files of a directory
In Python, you can use the glob
module to list directories and files that match a specified pattern. The glob
module provides a convenient way to search for files and directories in a directory structure using wildcard patterns. Here's how you can use it with some examples:
Importing the glob
Module
First, you need to import the glob
module:
python
import glob
Listing All Directories
You can use the glob.glob()
function with the */
pattern to list all directories in a specific directory:
python
directories = glob.glob('/path/to/your/directory/*/')
for directory in directories:
print(directory)
This code will list all directories in the specified path.
Listing Files in a Directory
To list all files in a specific directory, you can use the *
pattern:
python
files = glob.glob('/path/to/your/directory/*')
for file in files:
print(file)
This code will list all files (not directories) in the specified path.
Filtering Directories or Files by a Specific Pattern
You can also use more specific patterns to filter directories or files based on your requirements. For example, if you want to list all directories that start with "dir_", you can use the following code:
python
directories = glob.glob('/path/to/your/directory/dir_*')
for directory in directories:
print(directory)
This code will only list directories that match the specified pattern.
Similarly, if you want to list all .txt
files in a directory, you can use the following code:
python
txt_files = glob.glob('/path/to/your/directory/*.txt')
for file in txt_files:
print(file)
Recursive Directory Listing
By using the **/
pattern, you can perform a recursive directory listing to search for directories or files in subdirectories as well. Here's an example that lists all .jpg
files recursively:
python
jpg_files = glob.glob('/path/to/your/directory/**/*.jpg', recursive=True)
for file in jpg_files:
print(file)
This code will list all .jpg
files in the specified directory and its subdirectories.
The glob
module is a powerful tool for listing directories and files based on patterns, making it a versatile choice for working with file systems in Python.