How can I change directory with Python pathlib

PythonPathlib

Python Problem Overview


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

Lets assume I create a Path object as follows:

from pathlib import Path
path = Path('/etc')

Currently I just know the following, but that seems to undermine the idea of pathlib.

import os
os.chdir(str(path))

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

In the Python 3.6 or above, os.chdir() can deal with Path object directly. In fact, the Path object can replace most str paths in standard libraries.

> os.chdir(path) Change the current working directory to path. > > This function can support specifying a file descriptor. The descriptor > must refer to an opened directory, not an open file. > > New in version 3.3: Added support for specifying path as a file > descriptor on some platforms. > > Changed in version 3.6: Accepts a path-like object.

import os
from pathlib import Path

path = Path('/etc')
os.chdir(path)

This may help in the future projects which do not have to be compatible with 3.5 or below.

Solution 3 - Python

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`

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLukasView Question on Stackoverflow
Solution 1 - PythonLukasView Answer on Stackoverflow
Solution 2 - PythonYan QiDongView Answer on Stackoverflow
Solution 3 - PythonAXOView Answer on Stackoverflow