Python: Make file lists from current directory using a wildcard
Python Basic: Exercise-111 with Solution
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/python-basic-exercise-111.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics