Question

I am trying to walk through tree of directories and search for data in output text files by defining a recursive function (and not using os.walk) in Python.

import os

def walkfn(dirname):
    if os.path.exists('output'):
        file1 = open('output')
        for line in file1:
            if line.startswith('Final value:'):
                print line
    else:
        for name in os.listdir(dirname):
            path = os.path.join(dirname, name)
            if os.path.isdir(path):
                print "'", name, "'"
                newdir = os.chdir(path)
                walkfn(newdir)

cwd = os.getcwd()
walkfn(cwd)

I am getting the following error:

Traceback (most recent call last):
  File "/home/Python Work/Test2.py", line 24, in <module>
    walkfn(cwd)
  File "/home/Python Work/Test2.py", line 19, in walkfn
    walkfn(newdir)
  File "/home/Python Work/Test2.py", line 12, in walkfn
    for name in os.listdir(dirname):
TypeError: coercing to Unicode: need string or buffer, NoneType found
Was it helpful?

Solution

os.chdir() returns None, not the new directory name. You pass that result to the recursive walkfn() function, and then to os.listdir().

There is no need to assign, just pass path to walkfn():

for name in os.listdir(dirname):
    path = os.path.join(dirname, name)
    if os.path.isdir(path):
        print "'", name, "'"
        os.chdir(path)
        walkfn(path)

You usually want to avoid changing directories; there is no need to if your code uses absolute paths:

def walkfn(dirname):
    output = os.path.join(dirname, '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(dirname):
            path = os.path.join(dirname, name)
            if os.path.isdir(path):
                print "'", name, "'"
                walkfn(path)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top