Python Program - Find All File with .txt Extension Present Inside a Directory
https://www.theitroad.com
here's a Python program that finds all the files with a .txt
extension inside a directory:
import os directory = input("Enter the directory path: ") # loop through all the files in the directory for filename in os.listdir(directory): # check if the file has a .txt extension if filename.endswith(".txt"): # print the file name print(filename)
In this program, we first use the input()
function to get the path of the directory from the user, and store it in the variable directory
.
We then use the os.listdir()
function to get a list of all the files in the directory, and loop through each file name using a for
loop.
Inside the loop, we check if the file name ends with the .txt
extension using the endswith()
method, and if it does, we print the file name using the print()
function.