0

Program for recursively printing files and directory in python #!/usr/bin/env python

import os

temp_path = os.getcwd()
path = temp_path.split("/")
print path[-1]

def recursive(wrkdir):

    for items in os.listdir(wrkdir):
        if os.path.isfile(items):
            print "---"+items

    for items in os.listdir(wrkdir):
        if os.path.isdir(items):
            print "---"+items
            #following call to recursive function doesn't work properly
            recursive("./"+items)

recursive(os.getcwd())
7
  • 2
    "./"+items is only going to be the path to the folder in the first level of the recursion. Maybe os.path.join(wrkdir, items) Commented Dec 8, 2015 at 12:29
  • The same for os.path.isdir, you need to provide the full path Commented Dec 8, 2015 at 12:30
  • so what's the solution to this Commented Dec 8, 2015 at 12:30
  • let there are 2 folder named as fol1, fol2 and 2 files names as file1.txt, file2,txt in "xyz" dir. so if we run above prog from xyz folder then os.getcwd() will be /home/user/xyz. so at first wrkdir contain /home/user/xyz and after os.path.isdir(items), recursive will be called by /home/user/xyz/fol1. which looks perfectly fine Commented Dec 8, 2015 at 12:36
  • With the code above, the recursive function is called on ./fol1, and not the full path. Print wrkdir if you want to be sure. Commented Dec 8, 2015 at 12:47

2 Answers 2

2

You need to used the absolute file/directory path when checking for file/dir using os.path.isfile or os.path.isdir:

import os

def recursive(wrkdir):

    for item in os.listdir(wrkdir):
        if os.path.isfile(os.path.join(wrkdir, item)):
            print "--- {0}".format(items)

    for item in os.listdir(wrkdir):
        if os.path.isdir(os.path.join(wrkdir, item)):
            print "--- {0}".format(items)
            recursive(os.path.join(wrkdir, item))

recursive(os.getcwd())
Sign up to request clarification or add additional context in comments.

Comments

0

try this :

def recurse(cur_dir,level=0):
    for item_name in os.listdir(cur_dir):
        item = os.path.join(cur_dir,item_name)
        if os.path.isfile(item):
            print('\t'*level+'-',item_name)
        if os.path.isdir(item):
            print('\t'*level+'>',item_name)
            recurse(item,level+1)

recurse(os.getcwd())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.