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
.txtextension 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
.txtusingendswith().
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
filesofmy_dir. - Check if the file has extension
.txtusingendswith().
Related posts:
Python String join()
Python exec()
Python max()
Python Dictionary clear()
Python Program to Check If a List is Empty
Python Program to Print the Fibonacci sequence
Python Program to Print Output Without a Newline
Python String islower()
Python delattr()
Python Program to Get the Class Name of an Instance
Python Program to Randomly Select an Element From the List
Python Program Read a File Line by Line Into a List
Python Program to Shuffle Deck of Cards
Python String startswith()
Python Program to Convert Decimal to Binary Using Recursion
Python Program to Delete an Element From a Dictionary
Python sum()
Python Exception Handling Using try, except and finally statement
Python Anonymous / Lambda Function
Python object()
Python int()
Python String split()
Python Tuple
Python Directory and Files Management
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python Object Oriented Programming
Python Program to Multiply Two Matrices
Python List pop()
Python pow()
Python type()
Python frozenset()
Python Program to Get the File Name From the File Path