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:
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python Machine Learning Eqution Reference - Sebastian Raschka
Python range()
Python Set discard()
Python List remove()
Check If a File or Directory Exists in Java
Python isinstance()
Python dict()
Python round()
Python String splitlines()
Python Program to Differentiate Between del, remove, and pop on a List
Python Tuple index()
JUnit5 Programmatic Extension Registration with @RegisterExtension
Python String swapcase()
Python Dictionary update()
Python List append()
Python String lower()
Python bool()
Python callable()
Python pass statement
Python datetime
Python Set symmetric_difference_update()
Python String rindex()
Python Program Read a File Line by Line Into a List
How to get current date and time in Python?
Python String lstrip()
Python Program to Find the Largest Among Three Numbers
Python Set difference()
Python hash()
Python Program to Count the Number of Each Vowel
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python Multiple Inheritance