<p>我正在尝试创建一个遍历目录的walker。以下是我部分工作的输入和输出。我正在使用一个测试目录,但我想这是做在任何目录,这是导致一些问题。在</p>
<pre><code>[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
</code></pre>
<p>以下是目前为止的代码:</p>
^{pr2}$
<p>这将返回目录和文件,但我必须手动分配目录的名称。在</p>
<pre><code>testdir = directory_lister(path/to/testdir)
j = directory_lister(path/to/j)
etc
</code></pre>
<p>是否有一种自动化实例的方法,以便:</p>
<pre><code>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.
</code></pre>
<p>是否有:</p>
<pre><code>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??
</code></pre>
<p>上面的代码是错误的,因为对象x只是一个实例,而j,k,l必须手动定义。我是否必须使用另一个类或带有<strong>getattr</strong>的字典,但我总是遇到相同的问题。如果需要额外的信息,请询问,我希望我能说清楚。在</p>
<p>更新2</p>
<p>有没有办法通过下面的Anurag向DirLister添加其他复杂函数?所以当它到达一个文件,比如testdir/j/p时,它打印出文件p的第一行</p>
<pre><code>[IN] print testdir.j.p
[OUT] First Line of p
</code></pre>
<p>我已经为打印文件的第一行创建了一个类:</p>
<pre><code>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
</code></pre>
<p>只需要知道如何把它融入下面的课堂。谢谢您。在</p>
<p>不知道你在问什么,但这行吗?在</p>
<pre><code>for root,dirs,files in os.walk(/path/to/testdir/):
listers = dict((dir, directory_lister(dir)) for dir in dirs)
#now you can use:
listers['j']
listers['k']
listers['l']
</code></pre>