Table of Contents
In this example, you will learn to find all files with .txt extension present inside a directory.
To understand this example, you should have the knowledge of the following Python programming topics:
1. Example 1: Using glob
import glob, os os.chdir("my_dir") for file in glob.glob("*.txt"): print(file)
Output
c.txt b.txt a.txt
Using glob
module, you can search for files with certain extensions.
os.chdir("my_dir")
sets the current working directory to/my_dir
.- Using a for loop, you can search for files with
.txt
extension usingglob()
. *
denotes all files with a given extension.
2. Example 2: Using os
import os for file in os.listdir("my_dir"): if file.endswith(".txt"): print(file)
Output
a.txt b.txt c.txt
In this example, we use endswith()
method to check the .txt
extension.
- Using a for loop, iterate through each file of directory
/my_dir
. - Check if the file has extension
.txt
usingendswith()
.
3. Using os.walk
import os for root, dirs, files in os.walk("my_dir"): for file in files: if file.endswith(".txt"): print(file)
Output
c.txt b.txt a.txt
This example uses the walk()
method of the os
module.
- Using a for loop, iterate through each
files
ofmy_dir
. - Check if the file has extension
.txt
usingendswith()
.
Related posts:
Python Program to Check Leap Year
Python Set difference_update()
Python Set issubset()
Python Program to Count the Occurrence of an Item in a List
Python Program to Solve Quadratic Equation
Python String istitle()
Python String isidentifier()
Python Statement, Indentation and Comments
Python Program to Merge Mails
Python Program to Create a Countdown Timer
Python range()
Python dir()
Python print()
Python Program to Sort a Dictionary by Value
Python Program to Iterate Through Two Lists in Parallel
Python bin()
Python Program to Create Pyramid Patterns
Python Program to Transpose a Matrix
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
APIs in Node.js vs Python - A Comparison
Python input()
Python enumerate()
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python String join()
Python Program to Parse a String to a Float or Int
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python any()
Python Custom Exceptions
Python List index()
Python hasattr()
Python float()