Pet*_*etr 5 python regex string path
我需要更改当前文件的前缀。
示例如下:
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')
Run Code Online (Sandbox Code Playgroud)
可以看出,硬编码很容易。但是有没有办法自动化这一步呢?我想做的事情有一个伪想法:
str(file).split('/')[-1] = str(file_prexif) + str('_') + str(file).split('/')[-1]
Run Code Online (Sandbox Code Playgroud)
我只想更改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}'))
Run Code Online (Sandbox Code Playgroud)
\Users\my_name\PYTHON\Playing_Around\A_testing_lm.py
Run Code Online (Sandbox Code Playgroud)
使用file.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)
Run Code Online (Sandbox Code Playgroud)
/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
Run Code Online (Sandbox Code Playgroud)