Open In App

Python – List Files in a Directory

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with files in Python, a problem arises with how to get all files in a directory. In this article, we will cover different methods of how to list all file names in a directory in Python.

Performing file operations is a must-have skill for programmers. Learning file operations using Python helps in managing files, integrating files with your programs, building real-world programs, etc. We will cover the most fundamental concept of listing all files present under a specific directory.

We will cover two modules and their respective functions for this tutorial on listing file names and details in a directory. 

What is a Directory in Python?

A Directory, sometimes known as a folder, is a unit organizational structure in a computer’s file system for storing and locating files or more folders. Python now supports several APIs to list the directory contents. For instance, we can use the Path.iterdir, os.scandir, os.walk, Path.rglob, or os.listdir functions. 

Directory in use: gfg

Files in a directory

How to List Files in a Directory in Python

There are multiple ways of listing all the files in a directory. In this article, we will discuss the below modules and their functions to fetch the list of files in a directory. We will cover a total of 5 ways with examples to check the list of files in a directory.

  1. Using OS Module
  2. Using glob Module 

List Files in a Directory Using Os Module in Python

We can use these 3 methods of the OS module, to get a list of files in a directory.

  • os.listdir() Method
  • os.walk() Method
  • os.scandir() Method

Using os.listdir() method to get the list of files

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

Syntax: os.listdir(path)

Parameters:

  • Path: Path of the directory

Return Type: returns a list of all files and directories in the specified path

Example 1: Get a list of all files in a directory

In this example, the os module is imported to interact with the operating system. The listdir function is used to obtain a list of all files and directories in the specified path (“C://Users//Vanshi//Desktop//gfg”). The result is then printed, displaying the names of files and directories present in the specified location.

Python3




# import OS module
import os
# Get the list of all files and directories
dir_list = os.listdir(path)
print("Files and directories in '", path, "' :")
# prints all files
print(dir_list)


Output:

Example 2: Get all the files and no folders

In this example, the Python program prompts the user for a folder path, and lists and prints the files in that directory, utilizing the os module for directory interaction and filtering files from the obtained list.

Python3




import os
print("Python Program to print list the files in a directory.")
Direc = input(r"Enter the path of the folder: ")
print(f"Files in the directory: {Direc}")
files = os.listdir(Direc)
# Filtering only the files.
files = [f for f in files if os.path.isfile(Direc+'/'+f)]
print(*files, sep="\n")


Example 3: Get only ‘.txt’ files from the directory

In this example, the Python script utilizes the os module to iterate through files in the current directory. It selectively prints only the names of files ending with “.txt,” effectively listing text files present in the directory.

Python3




# import OS
import os
for x in os.listdir():
    if x.endswith(".txt"):
        # Prints only text file present in My Folder
        print(x)


 Output:

Using os.walk() method to access files in a Directory tree

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

Syntax: os.walk(top, topdown, onerror, followlinks)

Parameters:

  • top: It is the top directory from which you want to retrieve the names of the component files and folders.
  • topdown: 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 top down.
  • onerror: It provides an error handler if an error is encountered 
  • followlinks: if set to True, visits folders referenced by system links 

Return: returns the name of every file and folder within a directory and any of its subdirectories.

Example: Get only ‘.txt’ files in a directory

 In this example, the Python script uses the os module to traverse through files in the specified directory (“C://Users//Vanshi//Desktop//gfg”) and its subdirectories. It identifies and prints the names of files with a “.txt” extension, populating the list variable with the desired text files.

Python3




# import OS module
import os
 
# This is my path
 
# to store files in a list
list = []
 
# dirs=directories
for (root, dirs, file) in os.walk(path):
    for f in file:
        if '.txt' in f:
            print(f)


Output:

Using os.scandir() method to list files in a Directory

os.scandir() is an efficient version of os.listdir() function. It was later released by Python and is supported for Python 3.5 and greater. 

Syntax: os.scandir(path)

Parameter:

  • Path-  Path of the directory.

Return Type: returns an iterator of os.DirEntry object.

Example: List all files and directories in a directory.

In this example, the Python script utilizes the os module to list files and directories in the specified path (“C://Users//Vanshi//Desktop//gfg”). It employs os.scandir() to obtain an iterator of os.DirEntry objects representing entries in the directory.

Python3




# import OS module
import os
 
# This is my path
 
# Scan the directory and get
# an iterator of os.DirEntry objects
# corresponding to entries in it
# using os.scandir() method
obj = os.scandir()
 
# List all files and directories in the specified path
print("Files and Directories in '% s':" % path)
for entry in obj:
    if entry.is_dir() or entry.is_file():
        print(entry.name)


Output:

List Files in a Directory Using the glob module in Python 

The glob module retrieves files/path names matching a specified pattern. Below are the ways by which we can list files in a directory using the glob module:

  • glob() Method
  • iglob() method

Using the glob() method to get all files in a directory

With glob, we can use wild cards (“*, ?, [ranges]) to make path retrieval more simple and convenient.

Syntax: glob.glob(pathname, *, recursive=False)

Parameters:

  • pathname: The path of the directory or the pattern to match.
  • recursive (Optional): A boolean parameter (default value is set to False) that indicates whether the search should be recursive, i.e., whether it should include subdirectories.

Returns:

  • List of matching file paths

Example: Python file matching and printing using glob() method

Python3




import glob
 
# This is my path
path = "C:\\Users\\Vanshi\\Desktop\\gfg"
 
# Using '*' pattern
print('\nNamed with wildcard *:')
for files in glob.glob(path + '*'):
    print(files)
 
# Using '?' pattern
print('\nNamed with wildcard ?:')
for files in glob.glob(path + '?.txt'):
    print(files)
 
 
# Using [0-9] pattern
print('\nNamed with wildcard ranges:')
for files in glob.glob(path + '/*[0-9].*'):
    print(files)


Output:

Using iglob() method to list files in a directory 

iglob() method can be used to print filenames recursively if the recursive parameter is set to True. This is used for big directories as it is more efficient than glob() method.

Syntax: glob.iglob(pathname, *, recursive=False)

Parameter: 

  • pathname = Path of the directory.
  • recursive (Optional)= A boolean parameter (default value is set to False) that indicates whether the search should be recursive, i.e., whether it should include subdirectories.

Returns: Iterator of matching file paths

Example: Print paths matching the specified pattern in a directory.

In this example, the Python script utilizes the glob module to find and print paths matching the specified pattern (“C:\Users\Vanshi\Desktop\gfg**\*.txt”). It employs glob.iglob() to return an iterator, which is then used to print the paths of all text files present in the specified directory and its subdirectories.

Python3




import glob
 
# This is my path
path = "C:\\Users\\Vanshi\\Desktop\\gfg**\\*.txt"
 
 
# It returns an iterator which will
# be printed simultaneously.
print("\nUsing glob.iglob()")
 
# Prints all types of txt files present in a Path
for file in glob.iglob(path, recursive=True):
    print(file)


Output:

These are the 5 ways you can use to get details of files and directories in a directory. Python has provided multiple built-in methods that you can use to know the files present in a directory. This tutorial showed easy methods with examples to understand how to get file listings with the os module and glob module.

Similar reads:



Last Updated : 18 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads