Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Python way to walk a directory tree?

I feel that assigning files, and folders and doing the += [item] part is a bit hackish. Any suggestions? I'm using Python 3.2

from os import * from os.path import *  def dir_contents(path):     contents = listdir(path)     files = []     folders = []     for i, item in enumerate(contents):         if isfile(contents[i]):             files += [item]         elif isdir(contents[i]):             folders += [item]     return files, folders 
like image 971
Mike Avatar asked Jul 10 '11 05:07

Mike


People also ask

How do I walk a directory in Python?

To traverse the directory in Python, use the os. walk() function. The os. walk() function accepts four arguments and returns 3-tuple, including dirpath, dirnames, and filenames.

What is walk function in Python?

Python method walk() generates the file names in a directory tree by walking the tree either top-down or bottom-up.


2 Answers

Take a look at the os.walk function which returns the path along with the directories and files it contains. That should considerably shorten your solution.

like image 128
Sanjay T. Sharma Avatar answered Sep 22 '22 06:09

Sanjay T. Sharma


os.walk and os.scandir are great options, however, I've been using pathlib more and more, and with pathlib you can use the .glob() method:

root_directory = Path(".") for path_object in root_directory.glob('**/*'):     if path_object.is_file():         print(f"hi, I'm a file: {path_object}")     elif path_object.is_dir():         print(f"hi, I'm a dir: {path_object}")   
like image 32
monkut Avatar answered Sep 24 '22 06:09

monkut