💻
Code Snippet
  • Overview
  • General
    • Anaconda
  • GUI
    • PyQT
      • Qt Design
  • Pandas
    • Read Data
    • Replace
  • Articles
    • Python. PyQt
    • Offline Payment Wallet With Django
    • Documentation Encrypt File
    • Play With Pillow
  • Fontend
    • Snippet
    • Hugo
    • JavaScript
      • Form Validation
  • Finance
    • Library
      • yfinance
  • Notebook
    • Untitled
    • Snippet
  • Python
    • Download file
    • Date and Time
    • Snippet
    • Compile .exe
    • Overview
    • Google
      • Samples for Google Workspace
      • Drive
      • GoogleSheet
    • Virtual environment
    • Database
      • Pickle()
    • Datatypes
      • Excel
      • Dictionary
        • xmltodict()
    • File Handling
      • shutil()
      • Get the File Name
      • Get the Full Path
      • Check the File Size
      • Get File Creation Date
      • Find All File
        • Untitled
    • Dictionary
      • Convert Two Lists
  • Data Science
    • HTTP requests
  • Google Workspace
    • Overview
    • Apps Script
      • ์Note
      • Overview
      • Snippet
        • HTML Service
        • Fetch API
      • Quickstart
      • Google Sheets
        • Overview
          • Snippet
        • Fundamentals
          • Macros & Custom Functions
          • Spreadsheets, Sheets, and Ranges
          • Working with Data
          • Data Formatting
          • Chart and Present Data
        • Built-in Google Services
        • Fetch and format API data
        • Connected Sheets
  • Git
  • Mini Lab
    • Line
    • Python
  • Function
    • Python
      • Date&Time
  • Database
    • SQLite
      • Example
Powered by GitBook
On this page
  • Find All File with .txt Extension Present Inside a Directory
  • Example 1: Using glob
  • Example 2: Using os
  • Using os.walk

Was this helpful?

  1. Python
  2. File Handling

Find All File

PreviousGet File Creation DateNextUntitled

Last updated 3 years ago

Was this helpful?

Find All File with .txt Extension Present Inside a Directory

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 topics:

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

Example 2: Using os

import os

for file in os.listdir("my_dir"):
    if file.endswith(".txt"):
        print(file)

Output

a
{21: 'b', 14: 'c'}

pop() also returns the value of the key passed.

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
https://www.programiz.com/python-programming/examples/find-txt-files
Python programming
Python File I/O
Python Directory and Files Management
Python for Loop