TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Loop Through Files in a Directory
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Loop Through Files in a Directory

Last updated: Nov 28, 2023 11:42 pm
By Harsh S.
Share
7 Min Read
Loop Through Files in a Directory using Python
SHARE

In this tutorial, you’ll learn how to loop through files in a directory using Python. This is a common task when working with files. Whether you want to perform operations on each file, read their contents, or process them in some way, you often need to iterate over files in a directory.

Contents
1. Using the os.listdir() function to iterate over files2. Using the os.scandir() function to loop through files3. Using the pathlib module to iterate over files4. Using the glob module to loop through files5. Using the os.walk() function to iterate over filesComparison of methodsCombining all methods used to loop through files in a directory

5 Ways to Loop Through Files in a Directory Using Python

We will cover the following methods and compare their advantages and disadvantages at the end.

  • Using the os.listdir() function
  • Using the os.scandir() function
  • Using the pathlib module
  • Using the glob module
  • Using the os.walk() function

Let us now read each and every method and understand how it works to loop through files in Python inside a directory.

Also Check: Python List All Files in a Directory

1. Using the os.listdir() function to iterate over files

To loop through files in a directory, you can use os.listdir() to get a list of filenames and then iterate through them.

Python Code:

import os

# Get the current working directory
cwd = os.getcwd()

# Get the list of files in the current directory
files = os.listdir(cwd)

# Loop through the files and print their names
for file in files:
  print(file)

2. Using the os.scandir() function to loop through files

Starting from Python 3.5, the os.scandir() function provides a more efficient way to loop through files and directories.

Python Code:

import os

# Get the current working directory
cwd = os.getcwd()

# Get the list of files in the current directory
files = os.scandir(cwd)

# Loop through the files and print their names
for file in files:
  print(file.name)

3. Using the pathlib module to iterate over files

Here’s a complete example of using pathlib to iterate over files in a directory:

Python Code:

from pathlib import Path

# Get the current working directory
cwd = Path.cwd()

# Get the list of files in the current directory
files = cwd.glob('*')

# Loop through the files and print their names
for file in files:
  print(file.name)

Must Read: Python Glob Example

4. Using the glob module to loop through files

The glob module is excellent for pattern matching and filtering files based on their names. Once the file list is fetched, we can easily loop through files.

Python Code:

import glob

# Get the list of files in the current directory
files = glob.glob('*')

# Loop through the files and print their names
for file in files:
  print(file)

5. Using the os.walk() function to iterate over files

The os.walk() method is useful when you need to loop through files in subdirectories recursively.

Python Code:

import os

# Get the current working directory
cwd = os.getcwd()

# Walk through the directory tree and print the names of all files
for root, dirs, files in os.walk(cwd):
  for file in files:
    print(os.path.join(root, file))

Comparison of methods

Here is a very brief but to-the-point comparison of different Python methods for looping through files in a directory.

MethodAdvantagesDisadvantages
os.listdir()Simple to useDoes not return file information
os.scandir()Returns file informationSlower than os.listdir()
pathlibObject-oriented interfaceNot as widely used as other methods
globSupports wildcardsCan be difficult to use for complex patterns
os.walk()RecursiveCan be slow for large directory trees
Method for iterating over files in a dir

Recommendation

The best method to use for looping through files in a directory depends on the specific needs of the application. In most cases, the os.listdir() function is the simplest and most efficient option. If file information is needed, the os.scandir() function can be used. The pathlib module provides a more object-oriented interface for working with files and directories. The glob module can be used for matching files with wildcards. The os.walk() function can be used for recursively walking through directory trees.

Must Read: How to Read/Write to a File in Python

Combining all methods used to loop through files in a directory

Here is a coding snippet consolidating all the different methods we have seen above. However, in this code, we have tried to cover some unique use cases. Check it out now.

Python Code:

# Get the list of files in the current directory that end with the `.txt` extension
txt_files = [file for file in os.listdir(os.getcwd()) if file.endswith('.txt')]

# Get the list of files in the current directory that are larger than 1 megabyte
large_files = [file for file in os.scandir(os.getcwd()) if file.stat().st_size > 1048576]

# Get the list of files in the current directory that were created in the last 24 hours
import datetime
from pathlib import Path
recent_files = [file for file in Path.cwd().glob('*') if file.stat().st_mtime > datetime.datetime.now() - datetime.timedelta(hours=24)]

# Get the list of files in the current directory that match the pattern `*.jpg`
import glob
jpg_files = glob.glob('*.jpg')

# Get the list of all files in the current directory tree
import os
all_files = []
for root, dirs, files in os.walk(os.getcwd()):
  for file in files:
    all_files.append(os.path.join(root, file))

Also Check: Read File Line by Line in Python

Conclusion

Looping through files in a directory is a common task in Python. By understanding the different methods available, you can choose the best method for the specific needs of your application.

Happy coding!

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article File transfer on android to your computer File Transfer on Android (5 Ways)
Next Article Higher Order Functions in Python Code Higher Order Functions in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x