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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With