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 List pop()
Python String rjust()
Python Program to Add Two Matrices
Python Closures
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Program to Find HCF or GCD
Python abs()
Python Program to Print all Prime Numbers in an Interval
Python object()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Program to Differentiate Between del, remove, and pop on a List
Python Program to Trim Whitespace From a String
Python String isprintable()
Python bin()
Python Program to Print Hello world!
Python Program to Find LCM
Python File I/O Operation
Python memoryview()
Python callable()
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python String title()
Python String format()
Python Set add()
Python time Module
Python Program to Check Armstrong Number
Python Shallow Copy and Deep Copy
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Program to Compute all the Permutation of the String
Python dir()
Python Program to Check Whether a String is Palindrome or Not
Python Inheritance
Python String partition()