Change filename prefix in Path PosixPath object

Viewed 547

I need to change a prefix for a current file.

An example would look as follows:

from pathlib import Path
file = Path('/Users/my_name/PYTHON/Playing_Around/testing_lm.py')
# Current file with destination
print(file)

# Prefix to be used
file_prexif = 'A'

# Hardcoding wanted results.
Path('/Users/my_name/PYTHON/Playing_Around/A_testing_lm.py')

As can be seen hardcoding it is easy. However is there a way to automate this step? There is a pseudo - idea of what I want to do:

str(file).split('/')[-1] = str(file_prexif) + str('_') + str(file).split('/')[-1]

I only want to change last element of PosixPath file. However it is not possible to change only last element of string

2 Answers

file.stem accesses the base name of the file without extension.

file.with_stem() (added in Python 3.9) returns an updated Path with a new stem:

from pathlib import Path
file = Path('/Users/my_name/PYTHON/Playing_Around/testing_lm.py')
print(file.with_stem(f'A_{file.stem}'))
\Users\my_name\PYTHON\Playing_Around\A_testing_lm.py

Use file.parent to get the parent of the path and file.name to get the final path component, excluding the drive and root.

from pathlib import Path
file = Path('/Users/my_name/PYTHON/Playing_Around/testing_lm.py')

file_prexif_lst = ['A','B','C']

for prefix  in file_prexif_lst:
    p = file.parent.joinpath(f'{prefix}_{file.name}')
    print(p)
/Users/my_name/PYTHON/Playing_Around/A_testing_lm.py
/Users/my_name/PYTHON/Playing_Around/B_testing_lm.py
/Users/my_name/PYTHON/Playing_Around/C_testing_lm.py
Related