How can I change directory with Python pathlib

前端 未结 3 818
感情败类
感情败类 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:04

    Based on the comments I realized that pathlib does not help changing directories and that directory changes should be avoided if possible.

    Since I needed to call bash scripts outside of Python from the correct directory, I opted for using a context manager for a cleaner way of changing directories similar to this answer:

    import os
    import contextlib
    from pathlib import Path
    
    @contextlib.contextmanager
    def working_directory(path):
        """Changes working directory and returns to previous on exit."""
        prev_cwd = Path.cwd()
        os.chdir(path)
        try:
            yield
        finally:
            os.chdir(prev_cwd)
    

    A good alternative is to use the cwd parameter of the subprocess.Popen class as in this answer.

    If you are using Python <3.6 and path is actually a pathlib.Path, you need str(path) in the chdir statements.

提交回复
热议问题