6

問題自体だけでなく、質問を説明しようとしても問題があります。約 7 回の繰り返しで構成されるディレクトリ ツリーがあるので、次のようにします。rootdir/a/b/c/d/e/f/destinationdir

次のように、5 つのサブディレクトリ レベルを持つものもあれば、10 ものサブディレクトリ レベルを持つものもあります。

rootdir/a/b/c/d/destinationdir

また:

rootdir/a/b/c/d/e/f/g/h/destinationdir

唯一の共通点は、宛先ディレクトリの名前が常に同じであることです。glob 関数を使用する方法は次のとおりです。

for path in glob.glob('/rootdir/*/*/*/*/*/*/destinationdir'):
--- os.system('cd {0}; do whatever'.format(path))

ただし、これは正確な数の中間サブディレクトリを持つディレクトリに対してのみ機能します。その数を指定する必要がない方法はありますかsubdirectories(asterices); 言い換えれば、中間サブディレクトリの数に関係なく関数をdestinationdirに到達させ、それらを反復処理できるようにします。どうもありがとう!

4

5 に答える 5

5

これは、次の方法でより簡単に実行できると思いますos.walk

def find_files(root,filename):
    for directory,subdirs,files in os.walk(root):
        if filename in files:
            yield os.join(root,directory,filename)

もちろん、これではファイル名部分にグロブ式を含めることはできませんが、正規表現または fnmatch を使用してその内容を確認できます。

編集

または、ディレクトリを見つけるには:

def find_files(root,d):
    for directory,subdirs,files in os.walk(root):
        if d in subdirs:
            yield os.join(root,directory,d)
于 2012-07-12T19:41:04.787 に答える
4

インデントのレベルごとにパターンを作成できます (10必要に応じて増やします)。

for i in xrange(10):
    pattern = '/rootdir/' + ('*/' * i) + 'destinationdir'
    for path in glob.glob(pattern):
        os.system('cd {0}; do whatever'.format(path))

これは繰り返されます:

'/rootdir/destinationdir'
'/rootdir/*/destinationdir'
'/rootdir/*/*/destinationdir'
'/rootdir/*/*/*/destinationdir'
'/rootdir/*/*/*/*/destinationdir'
'/rootdir/*/*/*/*/*/destinationdir'
'/rootdir/*/*/*/*/*/*/destinationdir'
'/rootdir/*/*/*/*/*/*/*/destinationdir'
'/rootdir/*/*/*/*/*/*/*/*/destinationdir'
'/rootdir/*/*/*/*/*/*/*/*/*/destinationdir'

任意の深さのディレクトリを反復処理する必要がある場合は、アルゴリズムを 2 つのステップに分割することをお勧めします。すべての「destinationdir」ディレクトリがどこにあるかを調査する第 1 段階と、操作を実行する第 2 段階です。

于 2012-07-12T19:06:56.030 に答える
2

ファイルを探している場合は、Formic パッケージを使用できます(開示: 私が書きました)。これは、'**' ワイルドカードを使用して Apache Ant の FileSet Glob を実装します。

import formic
fileset = formic.FileSet(include="rootdir/**/destinationdir/*")

for file_name in fileset:
    # Do something with file_name
于 2012-07-13T00:29:09.413 に答える
2

Python 3 glob.globは、任意の数の中間ディレクトリを指定するためにダブル ワイルドカードを受け入れるようになりました

于 2018-08-06T08:24:31.050 に答える
1

findこれは、コマンドなどのより用途の広いツールを使用すると、はるかに簡単に実行os.systemできます (呼び出しは、UNIX のようなシステムを使用していることを示しているため、これは機能します)。

os.system('find /rootdir -mindepth 5 -maxdepth 10 -type d -name destinationdir | while read d; do ( cd $d && do whatever; ); done')

..ユーザーが指定した文字列をそのコマンドに入れる場合、これは非常に安全ではないことに注意してください。代わりに subprocess.Popen を使用して、シェルを実行し、引数を自分で分割する必要があります。ただし、示されているように安全です。

于 2012-07-12T19:34:03.130 に答える