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

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.