python pkgs) pathlib 알아보기

2021. 9. 22. 20:07분석 Python/Packages

728x90

목차

     

    Working Directory

    Get a path to the current Python file

    curr_file = pathlib.Path(__file__)
    print(curr_file)

     

     

    Get a path to the current working directory

    cwd = pathlib.Path.cwd()
    print(cwd)

     

    Get a first parent folder path

    parent folder 찾기 

    one_above = pathlib.Path.cwd().parent 
    print(one_above)

     

    Get an Nth parent folder path

    N번째 상위 폴더를 찾는 방법

    mul_above = pathlib.Path.cwd().parent.parent.parent
    mul_above = pathlib.Path.cwd().parents[1]
    print(mul_above)

    Join paths

    Create a directory if it doesn’t exist

    tgt_path = pathlib.Path.cwd().joinpath('reports')
    
    if not tgt_path.exists():
        tgt_path.mkdir()

     

    Create files

    reports라는 폴더에 파일 생성하기 

    tgt_path = pathlib.Path.cwd().joinpath('reports')
    
    tgt_path.joinpath('summer-sales.csv').touch(exist_ok=True)
    tgt_path.joinpath('winter-sales.txt').touch(exist_ok=True)

    Check if the path is a folder

    폴더가 있는 지 여부 확인

    tgt_path = pathlib.Path.cwd().joinpath('reports')
    
    print(tgt_path.is_dir())
    print(tgt_path.joinpath('summer-sales.csv').is_dir())

    Check if the path is a file

     

    tgt_path = pathlib.Path.cwd().joinpath('reports')
    
    print(tgt_path.is_dir())
    print(tgt_path.joinpath('summer-sales.csv').is_file())

     

    Get the name of the file

    tgt_path = pathlib.Path.cwd().joinpath('reports/summer-sales.csv')
    print(tgt_path.name)

    Get the file extension

    tgt_path = pathlib.Path.cwd().joinpath('reports/summer-sales.csv')
    print(tgt_path.suffix)
    #.csv

    Iterate over files in a folder

    tgt_path = pathlib.Path.cwd().joinpath('reports')
    
    for file in tgt_path.iterdir():
        print(file)

     

     

    https://towardsdatascience.com/still-using-the-os-module-in-python-this-alternative-is-remarkably-better-7d728ce22fb7

     

    Still Using the OS Module in Python? This Alternative is Remarkably Better

    Python’s OS module is a nightmare for managing files and folders. You should try Pathlib.

    towardsdatascience.com

    https://pbpython.com/pathlib-intro.html

     

    728x90