改变Path PosixPath对象中的文件名前缀



我需要更改当前文件的前缀。

示例如下:

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')

可以看出,硬编码它很容易。但是,是否有一种方法可以自动执行此步骤?这是我想要做的一个伪想法:

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

我只想更改PosixPath文件的最后一个元素。但是,不能只更改字符串

的最后一个元素。

file.stem访问无扩展名的文件基名。

file.with_stem()(在Python 3.9中添加)返回一个带有新词干的更新的Path:

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

使用文件。Parent:获取路径的父节点,file.name:获取最终的路径组件,不包括驱动器和根节点。

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

类似于@Mark Tolonen的回答,但使用file.with_name方法(对我来说比"stem"更容易记住)

from pathlib import Path
file = Path('/home/python/myFile.py')
prefix = 'hello'
new_file = file.with_name(f"{prefix}_{file.name}")
print(new_file)
OUTPUT:
/home/python/hello_myFile.py

最新更新