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 Capitalize the First Character of a String
Python Program to Find LCM
Python complex()
Python Program to Check if a Number is Positive, Negative or 0
Python Program to Compute the Power of a Number
Python datetime
Python String startswith()
Python pow()
Python Recursion
Python Program to Swap Two Variables
Python String swapcase()
Python Deep Learning Cookbook - Indra den Bakker
Python String isnumeric()
JUnit5 Programmatic Extension Registration with @RegisterExtension
Python String rstrip()
Python List sort()
Python String rjust()
Python Matrices and NumPy Arrays
Python Program to Find Factorial of Number Using Recursion
Python Program to Multiply Two Matrices
Python Inheritance
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python String endswith()
Python Function Arguments
Python globals()
Python Program to Differentiate Between del, remove, and pop on a List
Python Data Structures and Algorithms - Benjamin Baka
Debug a JavaMail Program
Python Program to Sort Words in Alphabetic Order
Python String isdecimal()
Python Tuple index()
Python Program to Check if a Number is Odd or Even