I am trying to create a walker that goes through directories. Here are the inputs and outputs which I have partly working. I am using a test directory but I would like this to be done on any directory which is leading to some problems.
[IN]: print testdir #name of the directory [OUT]: ['j','k','l'] #directories under testdir [IN]: print testdir.j [OUT]: ['m','n'] # Files under testdir.j
Here is the code so far:
class directory_lister: """Lists directories under root""" def __init__(self,path): self.path = path self.ex =  for item in os.listdir(path): self.ex.append(item) def __repr__(self): return repr(self.ex)
This returns the directories and files but I have to manually assign the names of the directories.
testdir = directory_lister(path/to/testdir) j = directory_lister(path/to/j) etc
Is there a way to automate instances such that:
for root,dirs,files in os.walk(/path/to/testdir/): for x in dirs: x = directory_lister(root) #I want j = directory_lister(path/to/j), k = directory_lister(path/to/k) and l = directory_lister(path/to/l) here.
Can there be a:
class directory_lister: def __init__(self,path): self.path = path self.j = directory_lister(path + os.sep + j) # how to automate this attribute
The code above is wrong as the object x only becomes an instance but j,k,l have to be defined manually. Do I have to use another class or a dictionary with getattr but I always run into the same problem. If any extra information is required please ask, I hope I made this clear.
For Bonus points.....
Is there a way to add other complex functions, so when it gets to a file say testdir/j/p, it prints out the first line of file p.
[IN] print testdir.j.p [OUT] 'First Line of p'
I have made a class for printing out the first line of the file:
class File: def __init__(self, path): """Read the first line in desired path""" self.path = path f = open(path, 'r') self.first_line = f.readline() f.close() def __repr__(self): """Display the first line""" return self.first_line
Just need to know how to incorporate it in the class. Thank you and sorry for asking so much...