Algorithm
-
Import the necessary module:
import os
-
Get the directory path from the user or specify it:
directory_path = input("Enter the directory path: ")
-
Check if the specified path is a valid directory:
if os.path.isdir(directory_path):
-
Initialize an empty list to store the names of .txt files:
txt_files = []
-
Use the
os.listdir()
function to get a list of all files in the directory:for file_name in os.listdir(directory_path):
-
Check if each file has a .txt extension:
if file_name.endswith(".txt"):
-
If it does, add the file name to the list:
txt_files.append(file_name)
-
After the loop, print or return the list of .txt files:
print("Text files in the directory:", txt_files)
-
If the specified path is not a valid directory, print an error message:
else:
print("Invalid directory path.")
Code Examples
#1 Code Example- Python Programing Using glob
Code -
Python Programming
import glob, os
os.chdir("my_dir")
for file in glob.glob("*.txt"):
print(file)
Copy The Code &
Try With Live Editor
Output
b.txt
a.txt
#2 Code Example- Python Programing Using os
Code -
Python Programming
import os
for file in os.listdir("my_dir"):
if file.endswith(".txt"):
print(file)
Copy The Code &
Try With Live Editor
Output
b.txt
c.txt
#3 Code Example- Using os.walk
Code -
Python Programming
import os
for root, dirs, files in os.walk("my_dir"):
for file in files:
if file.endswith(".txt"):
print(file)
Copy The Code &
Try With Live Editor
Output
b.txt
a.txt
Demonstration
Python Programing Example to Find All File with .txt Extension Present Inside a Directory-DevsEnv