List All Txt Files in a Directory in Python

Python Program to List All Txt Files in a Directory Using glob

# Python Program to List All Txt Files in a Directory Using glob


#importing glob and os
import glob, os


#set the current working directory as user directory
os.chdir("user")

for file in glob.glob("*.txt"):
    print(file)

Output:

test1.txt
test2.txt
test3.txt

Python Program to List All Txt Files in a Directory Using OS

# Python Program to List All Txt Files in a Directory Using OS

# importing os
import os


# for loop to check the extension using endswith()
for file in os.listdir("Documents"):
    if file.endswith(".txt"):
        print(file)

Output:

a.txt
b.txt
c.txt

Python Program to List All Txt Files in a Directory Using OS.walk

# Python Program to List All Txt Files in a Directory Using OS.walk

# importing os module
import os

for root, dirs, files in os.walk("user"):
    for file in files:
        if file.endswith(".txt"):
            print(file)

Output:


file1.txt
file2.txt
file3.txt

About The Author

Leave a Reply