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 pow()
Python Program to Return Multiple Values From a Function
Python Dictionary pop()
Python List clear()
Python String isalnum()
Python Program to Check Armstrong Number
Python Program to Trim Whitespace From a String
Python Program to Convert Two Lists Into a Dictionary
Python Set issuperset()
Python property()
Python Set intersection_update()
Python Program to Display Fibonacci Sequence Using Recursion
Deep Learning with Python - Francois Chollet
Python Namespace and Scope
Python Object Oriented Programming
Python String find()
Python Dictionary get()
Python String swapcase()
Python Decorators
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Program to Create a Long Multiline String
Python Machine Learning - Sebastian Raschka
Python Multiple Inheritance
Python Objects and Classes
Python Program to Get File Creation and Modification Date
Python Data Types
Python Get Current time
Python Program to Check the File Size
Python Program to Find the Sum of Natural Numbers
Python open()
Python Program to Find the Factorial of a Number
Python Program to Find LCM