0

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

2
  • Unfortunately, os.walk is still the most feasible folder listing mechanism even under python 3. Commented Jan 16, 2017 at 13:42
  • I would much rather use it! However it has been requested that I don't use os.walk :( Commented Jan 16, 2017 at 13:49

4 Answers 4

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

I can confirm I using linux :)
2

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)

Comments

1

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.

7 Comments

the f in your lookforfiles function appears as an unresolved reference, am I doing something wrong?
I caught that myself. My brain added code that my hands didn't get to. Just edited it lol.
haha No worries, happens to everyone! Although I am getting an error with your code: TypeError: coercing to Unicode: need string or buffer, NoneType found in the lookforfiles function on line: contents = os.listdir(basepath)
be sure the directory is correct and give os.listdir a try in your console with any directory. just so you can see the output.
Alright this works on my end just beware that when reading files sometimes it wont be able to tell the type and will throw and exception if it cant read the text.
|
0

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

TL;TR: Use os.listdir.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.