【发布时间】:2022-12-08 06:58:31
【问题描述】:
我想知道是否有一种巧妙的方法来设置 Path.name 属性。
我的代码基本上是这样的:
from pathlib import Path
mypath = Path("this/is/a/path")
mypath.name == "path"
>>> True
#now I want to change the name, or the top level folder name in the path
mypath.name = "panda" #does not work, since its a property
#only way I can think of:
mypath = mypath.parent.joinpath("panda")
这很丑陋,尤其是因为我实际上在一个所有东西都有更长名字的班级。 name 属性有 setter 吗?我找不到任何,但我也没有找到相反的......
【问题讨论】:
-
从文档中:路径是不可变的和可散列的。您不能更改名称,您必须创建一个派生自旧名称的新 Path 对象。