jeff_h
jeff_h

Reputation: 539

traverse directory structure in python recursively without os.walk

I am trying to write a python2 function that will recursively traverse through the whole directory structure of a given directory, and print out the results.

All without using os.walk

This is what I have got so far:

test_path = "/home/user/Developer/test"

def scanning(sPath):
    output = os.path.join(sPath, 'output')
    if os.path.exists(output):
        with open(output) as file1:
            for line in file1:
                if line.startswith('Final value:'):
                    print line
    else:
        for name in os.listdir(sPath):
            path = os.path.join(sPath, name)
            if os.path.isdir(path):
                print "'", name, "'"
                print_directory_contents(path)

scanning(test_path)

This is what I currently get, the script doesn't enter the new folder:

' test2'
'new_folder'

The issue is that it does not go further down than one directory. I would also like to able to indicate visually what is a directory, and what is a file

Upvotes: 0

Views: 3884

Answers (4)

Ashraf Fouda
Ashraf Fouda

Reputation: 88

Try this out with recursion it is much simple and less code

import os

def getFiles(path="/var/log", files=[]):
    if os.path.isfile(path):
        return files.append(path)
    for item in os.listdir(path):
        item = os.path.join(path, item)
        if os.path.isfile(item):
            files.append(item)
        else:
            files = getFiles(item, files)
    return files  



for f in getFiles("/home/afouda/test", []):
    print(f)

Upvotes: 2

Dan Temkin
Dan Temkin

Reputation: 1605

Try using a recursive function,

def lastline(fil):
    with open(fil) as f:
        for li in f.readlines():
            if li.startswith("Final Value:"):
                print(li)

## If it still doesnt work try putting 'dirs=[]' here
def lookforfiles(basepath):
    contents = os.listdir(basepath)

    dirs = []
    i = 0

    while i <= len(contents):
        i += 1

        for n in contents:
            f = os.path.join(basepath, n)

            if os.path.isfile(f):
                lastline(f)
                print("\n\nfile %s" % n)
            elif os.path.isdir(f):
                print("Adding dir")
                if f in dirs:
                    pass
                else:
                    dirs.append(f)

    else:   
        for x in dirs:
            print("dir %s" % x)
            lookforfiles(x)

sorry if this doesn't fit your example precisely but I had a hard time understanding what you were trying to do.

Upvotes: 1

rtkaleta
rtkaleta

Reputation: 691

This question is a duplicate of Print out the whole directory tree.

TL;TR: Use os.listdir.

Upvotes: 0

Try this:

import os

test_path = "YOUR_DIRECTORY"

def print_directory_contents(dir_path):
    for child in os.listdir(dir_path):
        path = os.path.join(dir_path, child)
        if os.path.isdir(path):
            print("FOLDER: " + "\t" + path)
            print_directory_contents(path)

        else:
            print("FILE: " + "\t" + path)

print_directory_contents(test_path)

I worked on windows, verify if still working on unix. Adapted from: http://codegists.com/snippet/python/print_directory_contentspy_skobnikoff_python

Upvotes: 6

Related Questions