为什么这个递归函数在python中不起作用

时间:2015-12-08 12:23:40

标签: python

用于在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())

2 个答案:

答案 0 :(得分:2)

使用os.path.isfileos.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())

答案 1 :(得分:0)

试试这个:

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