7

Python 2.7 の Mac で os.walk を使用してディレクトリを移動すると、スクリプトは「apps」、つまり appname.app を通過します。処理の後半で、エラーを処理するときにエラーが発生します。とにかくそれらを調べたくないので、私の目的のためには、これらのタイプの「ディレクトリ」を無視するのが最善です。

これが私の現在の解決策です:

for root, subdirs, files in os.walk(directory, True):
    for subdir in subdirs:
        if '.' in subdir:
            subdirs.remove(subdir)
    #do more stuff

ご覧のとおり、2 番目の for ループは、サブディレクトリの反復ごとに実行されます。これは、最初のパスでとにかく削除したいものがすべて削除されるため、不要です。

これを行うには、より効率的な方法が必要です。何か案は?

4

3 に答える 3

20

次のようなことができます(「。」を含むディレクトリを無視したい場合):

subdirs[:] = [d for d in subdirs if '.' not in d]

新しいリストを作成するのではなく、使用しsubdirs = ...ているのと同じリストを変更する必要があるため、(だけでなく)スライスの割り当てが必要です。os.walk

リストを繰り返しながら変更するため、元のコードが正しくないことに注意してください。これは許可されていません。

于 2012-05-16T14:41:23.387 に答える
0

おそらく、os.walk の Python ドキュメントのこの例が役立つでしょう。ボトムアップ(削除)から機能します。

# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))

あなたの目標について少し混乱しています。ディレクトリのサブツリーを削除しようとしてエラーが発生していますか、それともツリーをたどろうとして単純なファイル名 (ディレクトリ名を除く) をリストしようとしているだけですか?

于 2012-05-16T14:31:34.473 に答える
0

必要なのは、反復する前にディレクトリを削除することだけだと思います。

for root, subdirs, files in os.walk(directory, True):
        if '.' in subdirs:
            subdirs.remove('.')
        for subdir in subdirs:
            #do more stuff
于 2022-02-17T13:19:29.250 に答える