>  기사  >  백엔드 개발  >  Python 코드 세트 pathlib 애플리케이션 지정된 디렉토리의 모든 파일을 가져오는 방법

Python 코드 세트 pathlib 애플리케이션 지정된 디렉토리의 모든 파일을 가져오는 방법

WBOY
WBOY앞으로
2023-04-19 12:37:032104검색

(1) 다음 코드는 기본적으로 지정된 디렉터리 root_dir의 모든 파일을 재귀적으로 가져옵니다. recursive 매개 변수가 False로 지정된 경우 root_dir 디렉터리의 모든 파일만 가져오고 suffix_tuple의 경우 재귀 검색이 수행되지 않습니다. 매개변수를 지정하면 얻을 수 있습니다. 지정된 suffix 파일은 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 파일이 없기 때문입니다. 기계야, 인쇄가 비어있어

Python 코드 세트 pathlib 애플리케이션 지정된 디렉토리의 모든 파일을 가져오는 방법

위 내용은 Python 코드 세트 pathlib 애플리케이션 지정된 디렉토리의 모든 파일을 가져오는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제