Vinod K
Vinod K

Reputation: 2133

Python code to print directories recursively

I have the following code , but it traverses the 1st directory it finds and stops. I feel i have the recursive function which should have given the other directories too. Can anyone please point out what is wrong with this code.

def func(path,no):
    no=no+2
    for item in os.listdir(path):
        if os.path.isfile(path+"\\"+item):
            print no * "-" + " " + item
        if os.path.isdir(path+"\\"+item):
            path=path + "\\" + item
            print no * "-" + " " + item
            func(path,no)


path="D:\\Hello"
no=0
func(pah,no)

OUTPUT :

-- 1.txt
-- 2.txt
-- 3.txt
-- blue
---- 33.txt
---- 45.txt
---- 56.txt
---- Tere

"blue" & "tere" are the directories. There are more directories int the "HELLO" folder which is not printed.

Upvotes: 1

Views: 116

Answers (2)

Steinar Lima
Steinar Lima

Reputation: 7821

To walk through directories recursivly, use os.walk

import os

path = r'path\to\root\dir'
for root, dirs, files in os.walk(path):
    # Access subdirs and files

On another note:

  1. To join parts of a path together, use os.path.join. So instead of path+"\\"+item you could use os.path.join(path, item). This will work on all platforms, and you don't have to think about escaping slashes etc.
  2. A better way to print values is to use the format method. In your case you could write

    print '{} {}'.format(no*'-', item)` 
    

    instead of

    print no * "-" + " " + item
    

Upvotes: 5

Liteye
Liteye

Reputation: 2801

It's because you change the path value to path + "\\" + item when you first find a directory. Then os.path.isfile(path+"\\"+item) and os.path.isdir(path+"\\"+item) all return False.

It should be like this:

def func(path,no):
    no=no+2
    for item in os.listdir(path):
        if os.path.isfile(path+"\\"+item):
            print no * "-" + " " + item
        if os.path.isdir(path+"\\"+item):
            print no * "-" + " " + item
            func(path + "\\" + item,no)

Upvotes: 3

Related Questions