如何替换 Python pathlib.Path 中的子字符串?

How can I replace a substring in a Python pathlib.Path?

有没有一种简单的方法可以替换 Python 中 pathlib.Path 对象中的子字符串? pathlib module is nicer in many ways 而不是将路径存储为 str 并使用 os.pathglob.glob 等,它们内置于 pathlib。但是我经常使用遵循某种模式的文件,并且经常替换路径中的子字符串来访问其他文件:

data/demo_img.png
data/demo_img_processed.png
data/demo_spreadsheet.csv

以前我可以做:

img_file_path = "data/demo_img.png"
proc_img_file_path = img_file_path.replace("_img.png", "_img_proc.png")
data_file_path = img_file_path.replace("_img.png", "_spreadsheet.csv")

pathlib 可以用 with_suffix() 方法替换文件扩展名,但只接受扩展名作为有效后缀。解决方法是:

import pathlib
import os


img_file_path = pathlib.Path("data/demo_img.png")
proc_img_file_path = pathlib.Path(str(img_file_path).replace("_img.png", "_img_proc.png"))
# os.fspath() is available in Python 3.6+ and is apparently safer than str()
data_file_path = pathlib.Path(os.fspath(img_file_path).replace("_img.png", "_img_proc.png"))

转换为字符串以进行替换并重新转换为 Path 对象似乎很费力。假设我从来没有 img_file_path 的字符串形式的副本,并且必须根据需要转换类型。

你是对的。将Path p中的old换new,需要:

p = Path(str(p).replace(old, new))

编辑

我们把 Path p 变成 str 所以我们得到这个 str 方法:

Help on method_descriptor:

replace(self, old, new, count=-1, /)

Return a copy with all occurrences of substring old replaced by new.

否则我们会得到这个 Path 方法:

Help on function replace in module pathlib:

replace(self, target)

Rename this path to the given path, clobbering the existing destination if it exists, and return a new Path instance pointing to the given path.

我最近遇到了类似的问题,在寻找解决方案时发现了这个帖子。与接受的答案相反,我没有将 pathlib.Path 对象转换为字符串。相反,我使用了它的 parent and name attributes (name is a string itself), along with the joinpath() 方法。这是代码:

In [2]: from pathlib import Path

In [3]: img_file_path = Path('data/demo_img.png')

In [4]: parent, name = img_file_path.parent, img_file_path.name

In [5]: proc_fn = name.replace('_img.png', '_img_proc.png')
   ...: data_fn = name.replace('_img.png', '_spreadsheet.csv')

In [6]: proc_img_file_path = Path(parent).joinpath(proc_fn)
   ...: data_img_file_path = Path(parent).joinpath(data_fn)

In [7]: proc_img_file_path
Out[7]: WindowsPath('data/demo_img_proc.png')

In [8]: data_img_file_path
Out[8]: WindowsPath('data/demo_spreadsheet.csv')

这种方法的一个优点是它避免了在父位中进行不需要的替换的风险。

使用PurePath.with_name() 或PurePath.with_stem()