问题
The below class is a dynamic attribute generating directory walker by 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
Is there a way to add other complex functions to the DirLister by Anurag above? So when it gets to a file say testdir/j/p, it prints out the first line of file p.
[IN] print testdir.j.p
[OUT] First Line of p
I have made a class for printing out the first line of the file:
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
Just need to know how to incorporate it in the class below. Thank you.
回答1:
You should be able to accomplish this by checking to see if self.root
is a file or a directory in _load()
. Read the first line if it is a file and do os.listdir()
if it is a directory. Try the following:
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
I used your File
class, but you could also just put the code for getting the first line in _load()
instead of having a separate class to do it. Note that I also renamed _list
to _data
, since it will not always represent a list of files anymore.
来源:https://stackoverflow.com/questions/8524311/readline-feature-in-directory-lister-class