0

I am trying to make a script in Python to recursively list all the files in a folder recursively. This code only shows some of the files in the directory I run it in, and I can't figure out why. Any help you can give me is much appreciated.

import os

def look(dir, indent_level = 0):
    for each in os.listdir(dir):
        if os.path.isfile(each):
            print indent_level*' ' + each
        if os.path.isdir(os.getcwd() + "/" + each):
             print indent_level*'' + each
             os.chdir(str(os.getcwd()) + "/" + each)
             look(os.getcwd(), 4 + indent_level)

look(os.getcwd())

Edited by dlazzeri: n/a

2
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by dlazzeri
1

You have to use the absolute or full path.

##--------------------------------------------------------------------
def get_files(parent):
    files_list = os.listdir(parent)
    for a in files_list:
        full_name = os.path.join( parent, a )
        if os.path.isdir(full_name):
            get_files(full_name)
        else:
            print full_name

get_files("/home")

Edited by woooee: n/a

0

You have to use the absolute or full path.

##--------------------------------------------------------------------
def get_files(parent):
    files_list = os.listdir(parent)
    for a in files_list:
        full_name = os.path.join( parent, a )
        if os.path.isdir(full_name):
            get_files(full_name)
        else:
            print full_name

get_files("/home")

Thanks! It works now.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.