The Wayback Machine - https://web.archive.org/web/20240622174528/https://www.geeksforgeeks.org/find-all-the-files-in-a-directory-with-txt-extension-in-python/
Open In App

Find all the Files in a Directory with .txt Extension in Python

Last Updated : 03 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Directory traversal is a common operation performed by file locator in Operating Systems. The operating system offers elaborate methods for streamlining the search process and the choice to search for a selected filename/extension. This article will teach you how to find all the files in a directory with a .txt (text files) extension using Python. Several functions could perform the task efficiently. This article will go in-depth over the following methods:

  • Using the listdir function to obtain .txt files
  • Using the glob function to obtain .txt files
  • Using the walk function to obtain .txt files

For demonstration purposes, the following directory would be used:

Files in a Directory with .txt Extension in Python

 

Find all the Files in a Directory with .txt using listdir function

The listdir function, found inside the os library, is used to obtain all the files found within the directory specified by the argument to the function. The function returns a list containing all the files within the specified directory. The syntax for the function is:

listdir(path=None)

Example 

Firstly the path to the directory is specified in a variable. Then the variable is passed to the listdir function as an argument. The function returns a list of all filenames within the specified directory. A loop is run over each element of this list. In each loop iteration, a list’s element (containing filename) is checked to determine whether it ends with a .txt extension, using the endswith function. If it does, then the path to the directory is prepended to the filename, and the result is displayed. The process continues until all the list elements are exhausted. 

Python3




import os
 
# Path to the directory (absolute or relative)
dir = "C:\Users\Sauleyayan\Desktop\New folder"
 
# os.listdir return a list of all files within
# the specified directory
for file in os.listdir(dir):
 
        # The following condition checks whether
    # the filename ends with .txt or not
    if file.endswith(".txt"):
 
        # Appending the filename to the path to obtain
        # the fullpath of the file
        print(os.path.join(dir, file))


Output:

C:\Users\Sauleyayan\Desktop\New folder\bakup.txt
C:\Users\Sauleyayan\Desktop\New folder\buy.txt

Find all the Files in a Directory with .txt using the glob function

The glob library is a versatile library when it comes to filesystem processing. The library offers many methods which allow wildcard matching against the paths, which helps create minimal codes. For accomplishing the task at hand, the use of the glob function present inside the glob library would be made. The syntax of the function is as follows:

glob(pathname, *, recursive=False)
Returns a list of paths matching a pathname pattern.

Example 

The function takes into an argument a pathname (absolute or relative) along with optional wildcards. Hence, If the wildcards are not provided, then the function works simply as a directory traverser and returns a list of all filenames in the given directory. If wildcards are provided, only the filenames matching the given wildcard pattern will make it to the list. The following code utilizes the function to devise an answer to the problem.

Python3




import glob
 
# Path to the directory
dir = "_Path_to_dir_"
 
# Adding the wildcard of *.txt on the directory
dir_wild = dir + "\\" + "*.txt"
# for ubantu dir_wild = dir + '/' + '*.txt'
 
# The glob function would return a list of all
# filenames ending with .txt in the directory
# The loop iterates over all the those results
for file in glob.glob(dir_wild):
 
    # Displaying the absolute path to the file
    print(file)


Output:

C:\Users\Sauleyayan\Desktop\New folder\bakup.txt
C:\Users\Sauleyayan\Desktop\New folder\buy.txt

Find all the Files in a Directory with .txt using the walk function

A walk function present inside the os library generates the file names in a directory tree by walking the tree either top-down or bottom-up. Each directory in the tree rooted at the top (including the top itself) yields a 3-tuple (root: Prints out directories only from what you specified, dirs: Prints out sub-directories from the root, and files: Prints out all files from root and directories).

Example 

Firstly the path to the directory is defined similarly to the previous examples. Then in a loop, the walk function is called, and the variable storing the directory path is passed as an argument. As explained earlier, the function returns 3 values, namely the root, directories, and the files found in the given path. Where the directories and files are lists, and the root is a string. Inside the loop, all the filenames present inside the files list are iterated over in for a loop. In each iteration, the filename is checked to determine whether it ends with the .txt extension. If it does, then the full path to the file is displayed. Otherwise, the file is ignored. 

Python3




import os
 
# Path to the directory
dir = "_Path_to_dir_"
 
# The function walk returns a three tuple
# which is stored in separate variables
for (root, dirs, files) in os.walk(dir,
                                   topdown=True):
 
        # Iterating over the list of files
    for x in files:
 
        # Condition to check whether the file
        # ends with .txt extension or not
        if x.endswith(".txt"):
 
            # Appending the filename to the path to
            # obtain the fullpath of the file
            print(root + "\\" + x)


Output:

C:\Users\Sauleyayan\Desktop\New folder\bakup.txt
C:\Users\Sauleyayan\Desktop\New folder\buy.txt

Related Articles:

How to read multiple text files from a folder in Python

List all files of a certain type in a directory using Python



Similar Reads

Python - List files in directory with extension
In this article, we will discuss different use cases where we want to list the files with their extensions present in a directory using python. Modules Usedos: The OS module in Python provides functions for interacting with the operating system.glob: In Python, the glob module is used to retrieve files/pathnames matching a specified pattern. The pa
3 min read
Python program to find files having a particular extension using RegEx
Prerequisite: Regular Expression in Python Many of the times we need to search for a particular type of file from a list of different types of files. And we can do so with only a few lines of code using python. And the cool part is we don't need to install any external package, python has a built-in package called re, with which we can easily write
2 min read
Change case of all characters in a .txt file using Python
In this article, we will learn how to change the case of all characters present in a text file using Python. We will use Python methods Python upper() to change all characters to upper case, and Python lower() to change all characters to lower case. For example, If we have text file data.txt as shown below. Change all characters to uppercase from t
3 min read
How to move all files from one directory to another using Python ?
In this article, we will see how to move all files from one directory to another directory using Python. In our day-to-day computer usage we generally copy or move files from one folder to other, now let's see how to move a file in Python: This can be done in two ways:Using os module.Using shutil module.Source and Destination Folder Setup Before Ru
2 min read
List all files of certain type in a directory using Python
In python, there are several built-in modules and methods for file handling. These functions are present in different modules such as os, glob, etc. This article helps you find out many of the functions in one place which gives you a brief knowledge about how to list all the files of a certain type in a directory by using Python programming. So the
3 min read
Copy all files from one directory to another using Python
In this article, we will discuss how to copy all files from one directory to another using Python. This can be done using the shutil module. This module can be used in Python to perform operations on files and folders in a directory. Shutil package facilitates the access, movement, and removal of the files between directories. Method 1 : Using shut
2 min read
Getting all CSV files from a directory using Python
Python provides many inbuilt packages and modules to work with CSV files in the workspace. The CSV files can be accessed within a system's directories and subdirectories and modified or edited. The CSV file contents can both be printed on the shell, or it can be saved in the form of the dataframe and played with later. In this article, we will see
3 min read
How to print all files within a directory using Python?
The OS module is one of the most popular Python modules for automating the systems calls and operations of an operating system. With a rich set of methods and an easy-to-use API, the OS module is one of the standard packages and comes pre-installed with Python. In this article, we will learn how to print all files within a directory using Python. T
3 min read
Python List All Files In Directory And Subdirectories
Listing all files in a directory and its subdirectories is a common task in Python, often encountered in file management, data processing, or system administration. As developers, having multiple approaches at our disposal allows us to choose the most suitable method based on our specific requirements. In this article, we will see how we can list a
5 min read
Find line number of a specific string or substring or word from a .txt file in Python
Finding the line number of a specific string and its substring is a common operation performed by text editors or any application with some level of text processing capabilities. In this article, you will learn how to find line number of a specific string or substring or word from a .txt (plain text) file using Python. The problem in hand could be
4 min read
Practice Tags :