Find All Files with .txt Extension in Python
Finding all files with a specific extension in a directory is a common task in programming. Python provides several methods to accomplish this, as you'll see below.
To locate all files with the .txt extension:
Using glob:
import glob, os os.chdir("/mydir") for file in glob.glob("*.txt"): print(file)
Using os.listdir:
import os for file in os.listdir("/mydir"): if file.endswith(".txt"): print(os.path.join("/mydir", file))
Using os.walk:
This method is suitable for traversing a directory and its subdirectories:
import os for root, dirs, files in os.walk("/mydir"): for file in files: if file.endswith(".txt"): print(os.path.join(root, file))
Choose the method that best suits your specific requirements.
The above is the detailed content of How Can I Find All .txt Files in a Directory Using Python?. For more information, please follow other related articles on the PHP Chinese website!