【发布时间】:2011-12-18 02:02:18
【问题描述】:
我正在尝试创建一个遍历目录的 walker。这是我部分工作的输入和输出。我正在使用一个测试目录,但我希望在任何会导致一些问题的目录上执行此操作。
[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
只需要知道如何将它合并到下面的类中。谢谢。
【问题讨论】:
-
directory_lister所需的界面和功能究竟是什么? -
os.walk已经列出了所有的目录和文件,那么directory_lister的意义何在? -
@KarlKnechtel,该功能是为了方便地列出根目录下的目录。所以你只需指定根目录,其余的就很容易查看了。
-
这还不能回答这个问题。