首页 > 解决方案 > 将 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 转换为字符串,以便可以将所有文件合并到一个列表中?

标签: pythonfilepathglobpathlib

解决方案


与大多数其他 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__方法在源代码中可能看起来有点难看,正如您在上面看到的,它会导致更快的运行时。


推荐阅读