Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory-tree listing in Python

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

like image 445
Matt Avatar asked Sep 23 '08 12:09

Matt


People also ask

How do I list a directory tree in Python?

You can use the os. walk() method to get the list of all children of path you want to display the tree of. Then you can join the paths and get the absolute path of each file.

How do I list items in a directory in Python?

listdir() method gets the list of all files and directories in a specified directory. By default, it is the current directory. Beyond the first level of folders, os. listdir() does not return any files or folders.


2 Answers

This is a way to traverse every file and directory in a directory tree:

import os  for dirname, dirnames, filenames in os.walk('.'):     # print path to all subdirectories first.     for subdirname in dirnames:         print(os.path.join(dirname, subdirname))      # print path to all filenames.     for filename in filenames:         print(os.path.join(dirname, filename))      # Advanced usage:     # editing the 'dirnames' list will stop os.walk() from recursing into there.     if '.git' in dirnames:         # don't go into any .git directories.         dirnames.remove('.git') 
like image 141
Jerub Avatar answered Sep 22 '22 02:09

Jerub


You can use

os.listdir(path) 

For reference and more os functions look here:

  • Python 2 docs: https://docs.python.org/2/library/os.html#os.listdir
  • Python 3 docs: https://docs.python.org/3/library/os.html#os.listdir
like image 32
rslite Avatar answered Sep 18 '22 02:09

rslite