Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 416
emilrn Avatar asked Aug 25 '26 07:08

emilrn


1 Answers

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)

like image 57
Gabriel Samain Avatar answered Aug 26 '26 22:08

Gabriel Samain