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
Shailendra Bramhvanshi, Founder at Techaroha Solutions Private Limited and CEO at Newtum Solutions Private Limited. BlockChain Experts with 12 years of IT Experience in of all aspects of running Organization and Project Management. I have created different coins to help the business to bring more trust. Recently deployed a stable coin in India TrueINR and working on few cryptocurrency exchanges. My Team is being rated as a top 10 blockchain service provider in India by Silicon India