35

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, "").

Ger
  • 9,076
  • 10
  • 37
  • 48
  • What does "complementary" mean here? Do you mean the parent, as in `path.parent`? In that case, you could just do `other_path = path.parent / 'other_file.dat'` – Erik Cederstrand Apr 10 '18 at 08:32
  • Yes, that is what I was looking for to change the file name. Is there also a way to change a given part ? For example `some` in `other` in my path ? – Ger Apr 10 '18 at 21:49
  • Yes. Split the path, change the element you want, and join the path again: `path_parts = path.parts; path_parts[4] = 'other'; path=Path(*path_parts)` – Erik Cederstrand Apr 11 '18 at 08:35
  • 1
    Thanks, it works if you convert `parts` to list (tuple being immutable) `path_parts = list(path.parts)`. – Ger Apr 11 '18 at 09:04

2 Answers2

52

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')
Ashish Gulati
  • 315
  • 2
  • 6
Ger
  • 9,076
  • 10
  • 37
  • 48
1

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))
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • Yes, I can do something like `str(path).replace(path.name,"")`. But I wonder if there is an analog at `path.name` that return the complementary part. – Ger Apr 10 '18 at 08:07