将WindowsPath转换为字符串

2024-09-28 18:57:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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转换成字符串,这样我就可以把所有的文件放到一个列表中?在


Tags: path字符串textosdirglobfileparent
2条回答

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

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

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

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

^{pr2}$

与大多数其他Python类一样,来自pathlibWindowsPath类实现了一个非默认的“dunderstring”方法(__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内建函数实际上在幕后调用了“dunderstring”方法,因此结果非常相同。顺便说一句,您可以很容易地猜到直接调用“dunderstring”方法可以通过加快执行时间来避免某种程度的间接寻址。在

下面是我在笔记本电脑上做的测试结果:

^{pr2}$

即使在源代码中调用__str__方法可能看起来有点难看,正如您在上面看到的,它会导致更快的运行时。在

相关问题 更多 >