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
---- ...
Lucas
  • 3,376
  • 6
  • 31
  • 46
  • Take a look [here][1] it was already answered before [1]: http://stackoverflow.com/questions/5817209/browse-files-and-subfolders-in-python –  Dec 14 '13 at 01:58
  • That is not what I am looking for. – Lucas Dec 14 '13 at 02:23

1 Answers1

6

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"))]
Community
  • 1
  • 1
Idris
  • 997
  • 2
  • 10
  • 27
  • @Lucas What OS are you running? – Idris Dec 14 '13 at 02:39
  • Windows 8. Target will be CentOS 6.5 that scans a NFS share on a Windows Server. Paths will be like /mnt/nfs/share/foo/bar/foo/bar – Lucas Dec 14 '13 at 02:52
  • @Lucas Can't you go into it manually and select the folders then rename them by right clicking? – Idris Dec 14 '13 at 03:06
  • I could but there will be spawn every day MANY folders that have to be renamed. – Lucas Dec 14 '13 at 03:11
  • @Lucas If theres a bunch just hold SHIFT and go from top to bottom. It'll do all of them so you can rename with one click – Idris Dec 14 '13 at 03:13