Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

How do I get a list of all files (and directories) in a given directory in Python?

1 Answer

0 votes
by (106k points)
edited by

To traverse every file and directory in a directory tree you can use the following piece of code:-

import os for dirname, dirnames, filenames in os.walk('.'):

for subdirname in dirnames:

print(os.path.join(dirname, subdirname))

for filename in filenames:

      print(os.path.join(dirname, filename)) 

  • The first for loop in the above code prints the path to all subdirectories. 

  • The second for loop in the code prints path to all filenames.

Another way by which you can list all the Directory trees in Python is by using the following piece of code:-

os.listdir(path)

If you are looking for upskilling yourself in python you can join our Python Certification and learn from the industrial expert! 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 2, 2019 in Python by Sammy (47.6k points)

Browse Categories

...