Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change directory with Python pathlib

Tags:

python

pathlib

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))
like image 925
Lukas Avatar asked Jan 19 '17 12:01

Lukas


People also ask

How do I change directory in Python program?

Changing the Current Working Directory in Python To change the current working directory in Python, use the chdir() method. The method accepts one argument, the path to the directory to which you want to change. The path argument can be absolute or relative.

How does Pathlib work in Python?

With pathlib , file paths can be represented by proper Path objects instead of plain strings as before. These objects make code dealing with file paths: Easier to read, especially because / is used to join paths together. More powerful, with most necessary methods and properties available directly on the object.

What is Pathlib path in Python?

The pathlib module of Python makes it very easy and efficient to deal with file paths. The os. path module can also be used to handle path name operations. The difference is that path module creates strings that represent file paths whereas pathlib creates a path object.

How can we create a directory with the Pathlib module?

Create Directory in Python Using the Path. mkdir() Method of the pathlib Module. The Path. mkdir() method, in Python 3.5 and above, takes the path as input and creates any missing directories of the path, including the parent directory if the parents flag is True .


3 Answers

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.

like image 105
Lukas Avatar answered Oct 24 '22 02:10

Lukas


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.

like image 22
Yan QiDong Avatar answered Oct 24 '22 03:10

Yan QiDong


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`
like image 1
AXO Avatar answered Oct 24 '22 02:10

AXO