How to change directory using Python pathlib

How can I change a directory using the Python pathlib (Documentation) function?

Suppose 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)) 
+15
source share
4 answers

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

Since I needed to call bash scripts outside of Python from the correct directory, I decided to use the context manager for a cleaner way of changing directories like 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 one.

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

+12
source

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

os. chdir (path) Change the current working directory to the path.

This function may support specifying a file descriptor. The descriptor must refer to an open directory, not an open file.

New in version 3.3: Added support for specifying the 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 future projects that should not be compatible with 3.5 or lower.

+4
source

For those who are not afraid of a third-party library :

$ pip install path.py

then:

 from path import Path # Changing the working directory: with Path("somewhere"): # cwd in now 'somewhere' ... 

or if you want to do this without a context manager:

 Path("somewhere").cd() # cwd in now 'somewhere' 
+4
source

Using pathlib (available since version 3.4)

 from pathlib import Path Path("somewhere").cwd() 
0
source

Source: https://habr.com/ru/post/1014218/


All Articles