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')
我得到了错误
^{pr2}$我想这是因为当我需要glob一个字符串时,我正在尝试glob一个Windows文件路径。有没有办法可以把WindowsPath转换成字符串,这样我就可以把所有的文件放到一个列表中?在
您是对的,当您调用
glob.glob
时需要一个字符串。在代码的最后一行,parent_dir
是一个pathlib.Path
对象,不能与字符串'/*fits'
连接。您需要通过将parent_dir
传递给内置的str
函数来显式地将parent_dir
转换为字符串。在因此,代码的最后一行应该是:
为了进一步说明,请考虑以下示例:
^{pr2}$与大多数其他Python类一样,来自
pathlib
的WindowsPath
类实现了一个非默认的“dunderstring”方法(__str__
)。结果表明,该方法为该类返回的字符串表示形式正是表示您要查找的文件系统路径的字符串。这里有一个例子:str
内建函数实际上在幕后调用了“dunderstring”方法,因此结果非常相同。顺便说一句,您可以很容易地猜到直接调用“dunderstring”方法可以通过加快执行时间来避免某种程度的间接寻址。在下面是我在笔记本电脑上做的测试结果:
^{pr2}$即使在源代码中调用
__str__
方法可能看起来有点难看,正如您在上面看到的,它会导致更快的运行时。在相关问题 更多 >
编程相关推荐