2

下面的类是 Anurag 的动态属性生成目录遍历器。

import os

class DirLister(object):
    def __init__(self, root):
        self.root = root
        self._list = None

    def __getattr__(self, name):
        try:
            var = super(DirLister).__getattr__(self, name)
            return var
        except AttributeError:
            return DirLister(os.path.join(self.root, name))

    def __str__(self):
        self._load()
        return str(self._list)

    def _load(self):
        """
        load once when needed
        """
        if self._list is not None:
            return
        self._list = os.listdir(self.root) # list root someway

root = DirLister("/")
print root.etc.apache

有没有办法在上面的 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

只需要知道如何将它合并到下面的类中。谢谢你。

4

1 回答 1

2

您应该能够通过检查是否self.root_load(). 如果是文件则读取第一行,如果os.listdir()是目录则执行。尝试以下操作:

import os

class DirLister(object):
    def __init__(self, root):
        self.root = root
        self._data = None

    def __getattr__(self, name):
        try:
            var = super(DirLister).__getattr__(self, name)
            return var
        except AttributeError:
            return DirLister(os.path.join(self.root, name))

    def __str__(self):
        self._load()
        return str(self._data)

    def _load(self):
        """
        load once when needed
        """
        if self._data is not None:
            return
        if os.path.isfile(self.root):
            f = File(self.data)
            self._data = f.first_line
        else:
            self._data = os.listdir(self.root) # list root someway

我使用了您的File课程,但您也可以只输入用于获取第一行的代码,_load()而不是使用单独的课程来完成。请注意,我还重命名_list_data,因为它不再总是代表文件列表。

于 2011-12-15T18:20:22.270 回答