Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
4 views
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 (46k 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']

Or 

  • 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.

Syntax-

os.listdir(path)

Ex-

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 (106k points)
edited by

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:-

Learn python programming from an industry expert, and enroll in our Python programming course!

Related questions

+1 vote
2 answers
+2 votes
2 answers
0 votes
1 answer
asked Jul 18, 2019 in Python by Sammy (47.6k points)
+2 votes
2 answers
+2 votes
3 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...