我正在尝试创建一个遍历目录的步行者。这是我部分工作的输入和输出。我正在使用测试目录,但我希望在任何会导致一些问题的目录上执行此操作。
[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
有没有办法在下面的 Anurag 的 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
只需要知道如何将它合并到下面的类中。谢谢你。