python - 将 WindowsPath 转换为字符串

标签 python filepath glob pathlib

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 类一样,来自 pathlibWindowsPath 类实现了一个非默认的“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/

相关文章:

python - PySpark 数值窗口分组依据

testing - Robot Framework - 使用相对路径从不同的目录变体运行测试

Redis 查找匹配字符串的模式键

通过 win32com 涉及 Outlook 的 Python 脚本在双击时运行,但不通过任务计划程序运行

python - 如何防止意外分配到空的 NumPy View

python - 如何将这个元组的元组转换为其元素的计数?

regex - 将 glob 转换为正则表达式或让 Perl 处理 glob 模式

python - 知道路径的最后一部分和基目录时,在 python 中查找文件的绝对路径?

css - css 中的完整路径?

bash - 这个 bash 脚本如何知道我当前目录中的文件?