简体   繁体   English

设置pathlib Path的name属性 class

[英]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.

相关问题 pathlib.Path.home() 中的 pathlib 库错误:类型对象 'Path' 没有属性 'home' - pathlib library error in pathlib.Path.home() : type object 'Path' has no attribute 'home' pathlib.Path 的简单子类化错误:没有 _flavour 属性 - Error with simple subclassing of pathlib.Path: no _flavour attribute 如何将`__class__.__name__` 设置为类属性? - How to set `__class__.__name__` as class attribute? 用要创建的类名设置类的属性 - Set attribute of class with name of class being created 如何使 pathlib 模块的路径类在区分大小写的模式下工作? - How to make the Path Class of pathlib module work in case sensitive mode ? Python pathlib.Path 库总是从路径中剪切最后一个文件夹并将其添加到创建文件的名称中 - Python pathlib.Path library always cuts last folder from the path and adds it to the name of created file Python Pathlib - 带有空格问题的路径 - Python Pathlib - path with spaces issue pandas dataframe 与 pathlib 路径过滤 - pandas dataframe with pathlib Path filtering 如何使用 pathlib.Path().glob() 读入文件并将具有相同文件名的文件输出到另一个子文件夹中 - How to read in a file and output the file with the same file name into another subfolder using pathlib.Path().glob() 如何从 pathlib.path 获取给定文件所在的文件夹名称? - How to get folder name, in which given file resides, from pathlib.path?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM