ホームページ  >  記事  >  バックエンド開発  >  Pythonコードセットpathlibアプリケーションを使用して、指定されたディレクトリ内のすべてのファイルを取得する方法

Pythonコードセットpathlibアプリケーションを使用して、指定されたディレクトリ内のすべてのファイルを取得する方法

WBOY
WBOY転載
2023-04-19 12:37:032103ブラウズ

(1) 次のコードは、デフォルトで、指定されたディレクトリ root_dir 内のすべてのファイルを再帰的に取得します。再帰パラメータが False に指定されている場合、root_dir ディレクトリ内のすべてのファイルのみが取得され、再帰検索は実行されません。 suffix_tuple パラメータを指定すると、root_dir ディレクトリに指定したサフィックスファイルが取得できます。

from pathlib import Path

def get_all_files(root_dir,recursive=True,suffix_tuple=()):
    all_files=[]
    if Path(root_dir).exists():
        if Path(root_dir).is_dir():
            if recursive:
                for elem in Path(root_dir).glob("**/*"):
                    if Path(elem).is_file():
                        suffix=Path(elem).suffix
                        if not suffix_tuple:
                            all_files.append(elem)
                        else:
                            if suffix in suffix_tuple:
                                all_files.append(elem)
            else:
                for elem in Path(root_dir).iterdir():
                    if Path(elem).is_file():
                        suffix=Path(elem).suffix
                        if not suffix_tuple:
                            all_files.append(elem)
                        else:
                            if suffix in suffix_tuple:
                                all_files.append(elem)
        else:
            all_files.append(root_dir)
    return all_files

(2) 具体的な使用方法は以下の通りです。つまり、テストコードで、具体的なディレクトリパスを指定します。存在するディレクトリ

if __name__=="__main__":
    path="D:/gitee/oepkgs/mugen/testcases/cli-test/acl/oe_test_acl_defaulr_rule.sh"
    for elem in get_all_files(path):
        print(elem)
    print("-------------------------------------------------")
    path = "D:/gitee/oepkgs/mugen/testcases/cli-test/acl"
    for elem in get_all_files(path):
        print(elem)
    print("-------------------------------------------------")
    path = "D:/gitee/oepkgs/mugen/testcases/cli-test/acl"
    for elem in get_all_files(path,False):
        print(elem)
    print("-------------------------------------------------")
    path = "D:/gitee/oepkgs/mugen/testcases/cli-test/acl"
    for elem in get_all_files(path, True,(".sh",)):
        print(elem)
    print("-------------------------------------------------")
    path = "D:/gitee/oepkgs/mugen/testcases/cli-test/acl"
    for elem in get_all_files(path, True, (".json",)):
        print(elem)

実行結果は以下の通り、最初にファイルとしてパスを指定した場合はクエリ結果としてファイルがそのまま返され、最後に.jsonサフィックスを指定しています。デバッグ マシン上に json ファイルがありません。出力は空です。

Pythonコードセットpathlibアプリケーションを使用して、指定されたディレクトリ内のすべてのファイルを取得する方法

以上がPythonコードセットpathlibアプリケーションを使用して、指定されたディレクトリ内のすべてのファイルを取得する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はyisu.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。