Python: Make file lists from current directory using a wildcard
Wildcard File Lister
Write a Python program to make file lists from the current directory using a wildcard.
Sample Solution-1:
Python Code:
# Import the glob module, which allows you to search for files using wildcard patterns
import glob
# Use the glob module to get a list of all files in the current directory
file_list = glob.glob('*.*')
# Print the list of all files in the current directory
print(file_list)
# Specific files
# Use a wildcard pattern to search for Python (.py) files in the current directory
print(glob.glob('*.py'))
# Use a more specific pattern to search for files with names starting with a digit and any extension
print(glob.glob('./[0-9].*'))
Sample Output:
['main.py'] ['main.py'] []
Sample Solution-2:
Python Code:
# Import the Path class from the pathlib module to work with file paths
from pathlib import Path
# Iterate over all files and directories in the root directory ("/")
for path in Path("/").glob("*.*"):
# Print the path (file or directory) to the console
print(path)
Sample Output:
/.dockerenv
Python Code Editor:
Previous: Write a Python program to get numbers divisible by fifteen from a list using an anonymous function.
Next: Write a Python program to remove the first item from a specified list.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics