Reputation: 1
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())
Upvotes: 0
Views: 81
Reputation: 2723
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())
Upvotes: 2
Reputation: 1
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())
Upvotes: 0