How to list all folders and files recursively?

How can I get folders and files including files / subdirectory folders in python? I need an absolute path for each file / folder.

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

folder
-- file
-- folder1
---- folder1.1
------ file
------ folder1.1.1
-------- file
-- folder2
---- ...
+4
source share
1 answer

I quickly looked around and found out that it is quite easy. From Sven Marnah :

You can os.walk()for recursive iteration through the directory and all its subdirectories:

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

To create 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"))]
+4
source

All Articles