Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list all folders and files recursively? [duplicate]

Tags:

python-2.7

How can I get folders and files including files/folders of subdirectories in python? I need the absolute path of each file/folder.

I want to rename all folders and files. So I have to rename the folders first.

folder
-- file
-- folder1
---- folder1.1
------ file
------ folder1.1.1
-------- file
-- folder2
---- ...
like image 681
Lucas Avatar asked Dec 14 '13 01:12

Lucas


1 Answers

I took a quick look around and found out its pretty easy. From Sven Marnach:

You can us os.walk() to recursively iterate through a directory and all its subdirectories:

for root, dirs, files in os.walk(path):
    for name in files:
        if name.endswith((".html", ".htm")):
            # whatever

To build a list of these names, you can use a list comprehension:

htmlfiles = [os.path.join(root, name)
             for root, dirs, files in os.walk(path)
             for name in files
             if name.endswith((".html", ".htm"))]
like image 181
Idris Avatar answered Sep 20 '22 20:09

Idris