Python Program to Find All File with .txt Extension Present Inside a Directory


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

The “.txt” file extension is used to indicate a plain text file in the file system. A plain text file contains only human-readable text characters, without any special formatting or embedded objects. Text files contain only text characters and no special formatting, they are lightweight and can be easily opened and read by many different software applications.


Python Code :

The Below Python program finds all files with a .txt extension present inside a directory:


import os

directory = '/path/to/directory'  # replace with the directory path you want to search in

txt_files = []

# Loop through all files in the directory
for filename in os.listdir(directory):
    if filename.endswith('.txt'):
        txt_files.append(filename)

print('All text files in directory:', txt_files)

Here’s how the program works:

Import the os module, which provides a way to interact with the file system. Set the directory variable to the path of the directory you want to search in. Create an empty list txt_files to hold the names of all text files found in the directory. Loop through all the files in the directory using the os.listdir() function. For each file, check if its filename ends with the .txt extension using the str.endswith() method. If the file has a .txt extension, append its filename to the txt_files list. Finally, print the list of all text files found in the directory. You can modify the program to perform other actions on the text files, such as opening and reading their contents.


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co