+2 votes
in Python by (10.2k points)
edited by

Can someone tell me how to find all the files in directory with .txt extension in Python?

3 Answers

+1 vote
by (46.1k points)
edited by

Their are many methods to do it:

  • os.walk

 >>> import os

>>> path = '/user/Bluetooth/cramp/charm'
>>> text_files = [f for f in os.listdir(filedestination) if f.endswith('.txt')]
>>> text_files
['qwe-cn.txt', 'zxc-jp.txt', 'qwe-kr.txt', 'qwe-tw.txt', ... 'mac-10.txt']


  • Glob 
>>> import glob
>>> glob.glob('./*.txt')
['./Maths.txt', './physics.txt', './chem.txt', './bio.txt']

Or fnmatch.filter()

 import fnmatch, os

print fnmatch.filter(os.listdir("/qwe"), "*.tx?") # 
+1 vote
by (10.9k points)
edited by

You can use os.listdir() which returns a list containing all the names of the entries in the directory which is given by the path.




import os

for myfile in os.listdir("/mydict"):

   if file.endswith(".txt"):

       print(os.path.join("/mydict", myfile))

Hope this answer helps.

0 votes
by (107k points)

You can use the below-mentioned code:-

for root, dirs, files in os.walk(directory):

    for file in files:

        if file.endswith('.txt'):

            print file

You can use the following video tutorials to clear all your doubts:-

Related questions

+1 vote
2 answers
+3 votes
2 answers
0 votes
1 answer
asked Jul 18, 2019 in Python by Sammy (47.8k points)
+2 votes
2 answers
+2 votes
3 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !