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))
For those who do not fear a third-party library:
$ pip install path.py
then:
or if you want to do it without the context manager:
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:
A good alternative is to use the
cwd
parameter of thesubprocess.Popen
class as in this answer.If you are using Python <3.6 and
path
is actually apathlib.Path
, you needstr(path)
in thechdir
statements.In the Python 3.6 or above,
os.chdir()
can deal withPath
object directly. In fact, thePath
object can replace moststr
paths in standard libraries.This may help in the future projects which do not have to be compatible with 3.5 or below.