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

4

2 回答 2

31

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

于 2019-06-16T19:09:29.667 回答
3

你是对的,当你打电话时你需要一个字符串glob.glob。在代码的最后一行,parent_dir是一个pathlib.Path对象,不能与 string 连接'/*fits'。您需要parent_dir通过将其传递给内置str函数来显式转换为字符串。

因此,代码的最后一行应为:

fspec = glob.glob(str(parent_dir)+'/*fits')

为了进一步说明,请考虑以下示例:

>>> from pathlib import Path
>>> path = Path('C:\\')
>>> path
WindowsPath('C:/')
>>> str(path)
'C:\\'
>>>
于 2019-06-16T19:38:08.920 回答