0

trying to walk through a directory and subdirectories I am getting error in the following code. Here, I am trying to call the constructor recursively.

import os
from os.path import isfile, join

class CovPopulate:
    fileList = list()
    def __init__(self,path):
        self.path = path
        for f in os.listdir(self.path):
            if isfile(join(self.path,f)):
                if f.endswith(".txt"):
                    fileList.append(join(self.path,f))
            else:
                CovPopulate(f)

Traceback : -

 CovPopulate(r"C:\temp")
File "<pyshell#1>", line 1, in <module>
CovPopulate(r"C:\temp")


 File "C:/fuzzingresults/CovPopulate.py", line 11, in __init__
      fileList.append(join(self.path,f))
       NameError: global name 'fileList' is not defined

but, I have alread defined the fileList = list()

This time I 've checked for the synch errors :/

  • Why do you want to do this? –  Sep 13 '13 at 10:24
  • 2
    I can see absolutely no reason to make this a class. – Daniel Roseman Sep 13 '13 at 10:42
  • @DanielRoseman, i know there is not reason, but classes help in reuse, I could just make a function and be done with it, but I prefer to make seperate classes for code, classes help in namespaces because imports can clash. ALl my utility functions are defined in seperate classes in one single file. Is there something wrong in doing this? –  Sep 13 '13 at 11:08
  • @Tichodroma, what? recursive constructor?.. just for learning –  Sep 13 '13 at 11:09

1 Answers1

0

filelist is defined in the namespace of the CovPopulate class. I suggest to access it through self. Besides, I got problem when f is not a file nor a directory (symlinks, pipes, ...) so I added the isdir check. Finally, I got the code to work only if I pass the absolute path to CovPopulate. My __init__ function looks like this:

def __init__(self,path):
    self.path = path
    for f in os.listdir(self.path):
        if isfile(join(self.path,f)):
            if f.endswith(".txt"):
                self.fileList.append(join(self.path,f))
        elif isdir(join(self.path,f)):
            CovPopulate(join(self.path,f))
jorispilot
  • 483
  • 2
  • 6
  • it won't work. I tried your code and did this. besides, fileList is already defined inside the class itself.. why is a self needed? –  Sep 13 '13 at 11:10
  • Do you still get a `NameError`? – jorispilot Sep 13 '13 at 11:45
  • By the way, read this: http://stackoverflow.com/questions/707380/in-python-how-can-i-access-static-class-variables-within-class-methods – jorispilot Sep 13 '13 at 12:08
  • yes the post makes sense, i get it. I need to use static var for it to work. –  Sep 13 '13 at 13:46