简体   繁体   中英

Why this recursive function doesn't work in python

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())

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())

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM