2011-12-15 39 views
2

下面的類是由Anurag生成的動態屬性生成目錄漫遊器。Directory Lister類中的Readline功能

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 

只需要知道如何將它下面的類。謝謝。

回答

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,因爲它不再總是代表文件列表。

+0

我得到... TypeError:強制爲Unicode:需要字符串或緩衝區,找到NoneType。 f = File(self.data)有問題,我試過f = File(self._data),但沒有運氣。 – Neeran 2011-12-16 09:28:37