python - 将 WindowsPath 转换为字符串
问题描述
redpath = os.path.realpath('.')
thispath = os.path.realpath(redpath)
fspec = glob.glob(redpath+'/*fits')
thispath = os.path.realpath(thispath+'/../../../..')
p = Path(thispath)
userinput = 'n'
while (userinput == 'n'):
text_file = next(p.glob('**/*.fits'))
print("Is this the correct file path?")
print(text_file)
userinput = input("y or n")
parent_dir = text_file.parent.resolve()
fspec = glob.glob(parent_dir+'/*fits')
我收到错误
unsupported operand type(s) for +: 'WindowsPath' and 'str'
我认为这是因为当我需要 glob 一个字符串时,我试图 glob 一个 Windows 文件路径。有没有一种方法可以将 WindowsPath 转换为字符串,以便可以将所有文件合并到一个列表中?
解决方案
与大多数其他 Python 类一样WindowsPath
,from 类pathlib
实现了一个非默认的“ dunder string ”方法(__str__
)。事实证明,该方法为该类返回的字符串表示正是表示您正在查找的文件系统路径的字符串。这里有一个例子:
from pathlib import Path
p = Path('E:\\x\\y\\z')
>>> WindowsPath('E:/x/y/z')
p.__str__()
>>> 'E:\\x\\y\\z'
str(p)
>>> 'E:\\x\\y\\z'
str
内置函数实际上在后台调用了“ dunder string ”方法,因此结果完全相同。顺便说一句,你可以很容易地猜到,直接调用“ dunder string ”方法通过缩短执行时间来避免一定程度的间接性。
这是我在笔记本电脑上完成的测试结果:
from timeit import timeit
timeit(lambda:str(p),number=10000000)
>>> 2.3293891000000713
timeit(lambda:p.__str__(),number=10000000)
>>> 1.3876856000000544
即使调用该__str__
方法在源代码中可能看起来有点难看,正如您在上面看到的,它会导致更快的运行时。
推荐阅读
- javascript - 使用 ngComponentOutlet 的 Angular 材质选项卡
- javascript - 获取函数的未捕获(承诺中)错误
- visual-studio - 为什么查看 dtsx 文件会修改它?
- c# - 如何为 ExtensionDataObject 设置值?
- excel - 比较列中的单元格 (VBA)
- python - python - 连接两个数据框并越过行
- isabelle - 为什么我们不能在进行规则反转时*直接*对归纳定义的谓词进行案例分析?
- javascript - InfluxDB 2.0:组期间和总结持续时间
- java - 如何创建多个 Spring @RestController,每个都有自己的线程池?
- python-3.x - 如何排序在 plotly.graph_objects.Scatterpolar 图中显示类别的方式