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 时,我正试图对 Windows 文件路径进行 glob。有没有一种方法可以将 WindowsPath 转换为字符串,以便将所有文件 glob 到一个列表中?
最佳答案
与大多数其他 Python 类一样,来自 pathlib
的 WindowsPath
类实现了一个非默认的“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__
方法在源代码中可能看起来有点丑陋,正如您在上面看到的那样,它也会导致更快的运行时间。
关于python - 将 WindowsPath 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52825134/