List All Txt Files in a Directory in Python

List All Txt Files in a Directory in Python
(Last Updated On: 17/05/2023)

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

Leave a Reply

Your email address will not be published. Required fields are marked *