Program to List Files in Directory Python

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Topics Covered

Overview

Python is full of functionality and is known for its automation. In Python, almost everything is possible to do. One of the tasks we are focussing on today is 'List files in Directory' using Python. Several modules or packages can do "list files in directory using python" work for us, but 2 of the most popular modules we will see are: OS and glob. Before doing how to get the files in the directory, we will see what exactly is a directory. A directory is a place or a folder where our files or sub-folders are stored.

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

What is Directory?

A directory is a folder which a unit organizational structure in a computer’s for storing and locating files or more folders. Python now supports several APIs to list the directory contents.

List File in the Directory

Before we get into how to list files in directory using Python. We will see, what is a directory. A directory is a folder which a unit organizational structure in a computer’s for storing and locating files or more folders. Python now supports several APIs to list the directory contents.

Now, we need to learn how to list files in directory using Python from the path. We will be using Python to list the files in the directory. There are several methods:

  • OS module
  • glob module

Using the OS module to list the files in the directory

The OS module in Python provides the functionality for interacting with the OS(Operating System) like MAC OS, Windows, or Linux. This module comes under the Python standard utility modules. It provides an easy and efficient way to interact with the Operating system.

The OS module contains a lot of functionality:

  • checking the current directory(os.getcwd())
  • changing the directory(os.chdir())
  • copy, cut or paste the files from one directory to another(shutil.copytree())
  • listing the files in the directory(os.listdir())

Functions in OS to list the files in the directory:

  • os.listdir()
  • os.walk()
  • os.scandir()
Free Courses by top Scaler instructors
Python Course for Beginners With Certification: Mastering the Essentials
Java Course - Mastering the Fundamentals
DBMS Course - Master the Fundamentals and Advanced Concepts
JavaScript Course With Certification: Unlocking the Power of JavaScript
C++ Course: Learn the Essentials
Python and SQL for Data Science Course
Python Course for Beginners With Certification: Mastering the Essentials
Java Course - Mastering the Fundamentals
DBMS Course - Master the Fundamentals and Advanced Concepts
JavaScript Course With Certification: Unlocking the Power of JavaScript
C++ Course: Learn the Essentials
Python and SQL for Data Science Course

os.listdir()

In this method os.listdir(), it gets the list of all files and directories in a specified directory. It does not return any files or folders. By default, it is the current directory.

Syntax:

Parameters:

  • Path: It is the path to the directory.

Return Type:

It will return the list of all the files and folders in the given specified path.

Example 1: Getting all the lists in a directory

Code:

Output:

Explanation:

In the above piece of code, we first import the OS module, and next, we have to define the path for which we want to get the files. Now, the next step will be to use the os.listdir() function that will take the input path and return the list of files available in the specified path. It will return a list of file names present in the directory.

Example 2: To get only .txt files

Code:

Output:

Explanation:

In this piece of code, we will be using os.listdir() function to get only .txt files. we first import the OS module, and next, we have to define the path for which we want to get the files. Now, the next step will be to use the os.listdir() function that will take the input path and return the list of files available in the specified path. It will return a list of file names present in the directory. In the given list, we will use the for loop as each item of the list is a string, so by using the endswith() method of string, we will check any .txt file.

Scaler Placement Report and Statistics

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data
Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more

os.walk()

It returns the file names in the directory. This os.walk() function will return a list of files in the tree structure. The method loops through all of the directories in a tree.

Syntax:

Parameters:

  • top:

    It is the top directory from which you want to retrieve the names of the component files and folders.

  • topdown:

    It specifies that directories should be scanned from the top down when set to True. If this parameter is False, directories will be examined from the bottom up.

  • onerror:

    It provides an error handler if an error is encountered.

  • followlinks:

    If set to True, visits folders referenced by system links.

Return Type:

Returns the name of every file and folder within a directory and any of its subdirectories(list files in directory using Python).

Code:

Output:

Explanation:

For this code to get the files in the directory, we will use os.walk() function. First, we will import our OS module, as usual, and then we have to specify the directory path for which you want to get your files. Now we will use os.walk() in a for loop, this os.walk() function will return a tuple that contains the root of the path, the directory we are currently in and a list of the names of the file that we are receiving from the function. Now for all the files, we will print the file or for checking any specific file extension, we will be using the if statement for CSV files we will use .csv and return the list files in directory using Python with the .csv extension.

os.scandir()

Syntax:

Parameters:

  • Path: It is the path to the directory.

Return Type:

It returns an iterator of os.DirEntry object, and we get the list file in Directory using Python.

Note: os.DirEntry objects are intended to be used and thrown away after iteration as attributes and methods of the object cache their values and never refetch the values again. If the metadata of the file has been changed or if a long time has elapsed since calling os.scandir() method. we will not get up-to-date information.

Code:

Output:

Turn Learning into Career Growth

1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary
1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary

List File in Directory Using Glob Module

In Python, the glob module is used to list files in a directory matching a specified pattern. The pattern rules of glob follow standard Unix path expansion rules. It is also predicted that according to benchmarks it is faster than other methods to match pathnames in directories.

iglob()

It is the method that can be used to print the list of files directory in Python recursively if the recursive parameter is set to True.

Syntax:

Parameters:

  • Pathname: It is the path to the directory.

Return type:

It will return the list file in the directory along with the path.

Code:

Output:

Explanation:

This piece of code is a bit different from other codes because this code uses the glob module instead of the os module, so first, we will import the glob module, and then specify the path of the directory. For getting the files in the directory, we will be using the glob.iglob function, which will return the path of the files.

Conclusion

  • In this article, we have seen how to list files in a directory using Python.

  • First, we have seen what a is directory. A Directory also sometimes known as a folder is a unit organizational structure in a computer’s file system for storing and locating files or more folders.

  • Here, we have seen 2 modules and 4 functions to retrieve files in the directory.

  • We have used the OS and glob modules to list files in a directory using Python, and the functions used were:

    • os.walk()
    • os.listdir()
    • os.scandir()
    • glob.iglob()

Python Check if File Exists