我正在尝试创建一个通过目录的walker。这是我部分工作的输入和输出。我正在使用一个测试目录,但是我希望在导致某些问题的任何目录上完成此操作。在python中分配os.walk中的实例
[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
这是迄今为止代码:
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)
这将返回目录和文件,但我必须手动指定目录的名称。
testdir = directory_lister(path/to/testdir)
j = directory_lister(path/to/j)
etc
是否有办法来自动实例这样的:
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.
才会有:
class directory_lister:
def __init__(self,path):
self.path = path
self.j = directory_lister(path + os.sep + j) # how to automate this attribute of the class when assigned to an instance??
上面的代码是错误的,因为对象x只有成为一个实例,但j,k,l必须手动定义。我是否需要使用其他课程或字典getattr但我总是遇到同样的问题。如果需要任何额外的信息,请问,我希望我明确说明。
更新2
有没有办法通过下面阿努拉格添加其他复杂功能的DirLister?所以当它到达一个文件时会说testdir/j/p,它会打印出文件p的第一行。
[IN] print testdir.j.p
[OUT] First Line of p
我已经做了类打印出来的文件的第一行:
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
只需要知道如何将它下面的类。谢谢。
到底是什么`directory_lister`的期望的接口和功能? – 2011-12-13 17:49:13
`os.walk`已经列出了所有的目录和文件,那么`directory_lister`的含义是什么? – ekhumoro 2011-12-13 18:04:02
@KarlKnechtel,功能是方便地列出根目录下的目录。所以你只需指定根目录,其余的就很容易查看。 – Neeran 2011-12-14 09:22:11