How can I change directory with Python pathlib

前端 未结 3 817
感情败类
感情败类 2021-02-05 02:34

What is the intended way to change directory using the Python pathlib (Documentation) functionality?

Lets assume I create a Path object as foll

3条回答
  •  暖寄归人
    2021-02-05 03:06

    If you don't mind using a third-party library:

    $ pip install path

    then:

    from path import Path
    
    with Path("somewhere"):
        # current working directory is now `somewhere`
        ...
    # current working directory is restored to its original value. 
    

    or if you want to do it without the context manager:

    Path("somewhere").cd()
    # current working directory is now changed to `somewhere`
    

提交回复
热议问题