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 bin()
Java Program to Implement the Program Used in grep/egrep/fgrep
Python Set clear()
Python Program to Get the File Name From the File Path
Python abs()
Python max()
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Program to Get File Creation and Modification Date
Python frozenset()
Python object()
Python String expandtabs()
Python Program to Print Hello world!
Python Program to Find Sum of Natural Numbers Using Recursion
Python if...else Statement
Python Generators
Python String istitle()
Python String isnumeric()
Python Dictionary
Python Program to Find LCM
Python Program to Count the Number of Occurrence of a Character in String
Python pow()
Python Program to Find the Factors of a Number
Python String lstrip()
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python String rindex()
Python String isprintable()
Python Program to Check If a String Is a Number (Float)
Python id()
Python Set pop()
Python String rstrip()
Python Program to Make a Flattened List from Nested List
Python Machine Learning Eqution Reference - Sebastian Raschka