Algorithm


  1. Import the necessary module:

    • import os
  2. Get the directory path from the user or specify it:

    • directory_path = input("Enter the directory path: ")
  3. Check if the specified path is a valid directory:

    • if os.path.isdir(directory_path):
  4. Initialize an empty list to store the names of .txt files:

    • txt_files = []
  5. Use the os.listdir() function to get a list of all files in the directory:

    • for file_name in os.listdir(directory_path):
  6. Check if each file has a .txt extension:

    • if file_name.endswith(".txt"):
  7. If it does, add the file name to the list:

    • txt_files.append(file_name)
  8. After the loop, print or return the list of .txt files:

    • print("Text files in the directory:", txt_files)
  9. 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

x
+
cmd
c.txt
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

x
+
cmd
a.txt
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

x
+
cmd
c.txt
b.txt
a.txt
Advertisements

Demonstration


Python Programing Example to Find All File with .txt Extension Present Inside a Directory-DevsEnv