ディレクトリを通過するウォーカーを作成しようとしています。ここに私が部分的に取り組んでいる入力と出力があります。テストディレクトリを使用していますが、問題が発生しているディレクトリでこれを実行したいと考えています。
[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
以下のクラスに組み込む方法を知る必要があります。ありがとうございました。