【问题标题】:Set the name attribute of the pathlib Path class设置pathlib Path类的name属性
【发布时间】: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 对象。

标签: python pathlib


【解决方案1】:

您可以使用 with_name 方法,它会更干净并且正是该方法的设计目的。它确实会返回一个新的 Path 对象,因此您将覆盖 mypath 或将其另存为新对象。

mypath = mypath.with_name('panda')

【讨论】:

    猜你喜欢
    • 2019-07-22
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 2020-09-27
    • 2020-04-04
    • 2013-07-16
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多