Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a new Path object from parts of a current path with pathlib?

Tags:

I would like to change a part of a Path object with pathlib.

For example if you have a Path object:

import pathlib
path = pathlib.Path("/home/user/to/some/floder/toto.out")

How can I change the file name ? And get a new path with for example "/home/user/to/some/folder/other_file.dat" ?

Or more generally, one can I change one or several elements of that path ?

I can get the parts of the path:

In [1]: path.parts
Out[1]: ('/', 'home', 'user', 'to', 'some', 'floder', 'toto.out')

Thus, a workaround is to join the needed parts, make a new string and then a new path, but I wonder if there is a more convenient tool to do that.

EDIT

To be more precise, does it exist an equivalent to path.name that return the complementary part of the path : str(path).replace(path.name, "").

like image 660
Ger Avatar asked Apr 10 '18 08:04

Ger


People also ask

What does Pathlib path () do?

The pathlib is a Python module which provides an object API for working with files and directories. The pathlib is a standard module. Path is the core object to work with files.

What does Pathlib path return?

parts : returns a tuple that provides access to the path's components. name : the path component without any directory. parent : sequence providing access to the logical ancestors of the path. stem : final path component without its suffix.

What is Iterdir ()?

Methods of concrete path The . iterdir() method creates an iterator that lists the files randomly. Path().exists() checks whether the file/directory exists in a current path. Let's use the directory of the previous example (our current directory is /data ): In [*]: p = pathlib.

Is Pathlib path PathLike?

pathlib. Path (WindowsPath, PosixPath, etc.) objects are not considered PathLike : PY-30747.


2 Answers

In order to sum up the comments, the statements are the following:

  1. In order to change the file name
In [1]: import pathlib

In [2]: path = pathlib.Path("/home/user/to/some/folder/toto.out")

In [3]: path.parent / "other_file.dat"
Out[3]: PosixPath('/home/user/to/some/folder/other_file.dat')

  1. In order to change one part in the path
In [4]: parts = list(path.parts)

In [5]: parts[4] = "other"

In [6]: pathlib.Path(*parts)
Out[6]: PosixPath('/home/user/to/other/folder/toto.out')
like image 138
Ger Avatar answered Sep 19 '22 08:09

Ger


You can try using str.format to have variable filenames

Ex:

import pathlib
filename = "other_file.dat"    #Variable. 
path = pathlib.Path("/home/user/to/some/floder/{0}".format(filename))
like image 45
Rakesh Avatar answered Sep 17 '22 08:09

Rakesh