Search code examples
python-2.7listdir

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)

Solution

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