emilrn
emilrn

Reputation: 63

Python recursive function by using os.listdir()

I'm trying to make a recursive function by using os.listdir(), and I am having troble looping to all my directories and list out all the files and directories.
I know it's better using os.tree() for solving this kind of problem, but i want to see how to solve this by using os.listdir(). Here are my current code:

#!/bin/usr/py
from os.path import abspath
from os.path import isfile, isdir
import os
import sys

dir = sys.argv[1]

def recursive(dir):
    files = os.listdir(dir)
    for obj in files:
        if isfile(obj):
            print obj
        elif isdir(obj):
            print obj
            recursive(abspath(obj))

#no idea why this won't work???
recursive(dir)

Upvotes: 3

Views: 5807

Answers (2)

balaks80
balaks80

Reputation: 146

Thanks Gabriel and Emilrn ! this was exactly what I was looking for to recursively get the list of files from a parent directory provided for one of my projects. Just leaving the updated code here for someone who needs it later.

#!/bin/usr/py
import os
import sys

dir = sys.argv[1]

def recursive(dir):
    files = os.listdir(dir)
    for obj in files:
        
        if os.path.isfile(os.path.join(dir,obj)):
            print ("File : "+os.path.join(dir,obj))
        elif os.path.isdir(os.path.join(dir,obj)):
            recursive(os.path.join(dir, obj))
        else:
            print ('Not a directory or file %s' % (os.path.join(dir, obj))

recursive(dir)

Upvotes: 1

Gabriel Samain
Gabriel Samain

Reputation: 507

Your issue comes from abspath(obj), try replacing it by os.path.join(dir, obj) to have real path to your obj (I tested it on my env)

Upvotes: 2

Related Questions