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 Find the Square Root
Python open()
Deep Learning in Python - LazyProgrammer
Python Program to Create a Countdown Timer
Python String ljust()
Python Program to Get a Substring of a String
Python String casefold()
Python Statement, Indentation and Comments
Python for Loop
Python chr()
Python Dictionary copy()
Python Objects and Classes
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Deep Learning Cookbook - Indra den Bakker
Python __import__()
Python Program to Create Pyramid Patterns
Python memoryview()
Python id()
Python frozenset()
Python Set union()
Python Function Arguments
Python Set copy()
Python globals()
Python Program to Display the multiplication Table
How to Get Started With Python?
Python Directory and Files Management
Python List index()
Python String count()
Python String startswith()
Python Program to Convert Celsius To Fahrenheit
Python Set pop()