[英]Set the name attribute of the pathlib Path class
I was wondering if there was a neat way to set the Path.name attribute.我想知道是否有一种巧妙的方法来设置 Path.name 属性。
My code basically looks like this:我的代码基本上是这样的:
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")
this is pretty ugly, especially since I am actually in a class with longer names for everything.这非常丑陋,特别是因为我实际上在 class 中,所有内容的名称都更长。 Is there a setter for the name attribute?
name 属性有 setter 吗? I cant find any, but I also didnt find the opposite...
我找不到任何,但我也没有找到相反的......
You can use the with_name method which would be cleaner and exactly what the method is designed for.您可以使用with_name方法,它会更清晰并且正是该方法的设计目的。
However, it is not overwriting the name
attribute which is impossible because it is immutable.但是,它不会覆盖
name
属性,这是不可能的,因为它是不可变的。 It returns a new Path object so you will have overwrite mypath
or save it as something new.它返回一个新路径 object,因此您将覆盖
mypath
或将其另存为新路径。
mypath = mypath.with_name('panda')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.