- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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/
我正在处理的代码抛出错误 Unsupported operand type(s) for +: 'WindowsPath' and 'str' .我尝试了很多东西,但没有一个能解决这个问题(除了删除带
redpath = os.path.realpath('.') thispath = os.path.realpath(redpath) fspec = glo
我正在使用 pathlib 使用 Path 类管理我的 Python 项目中的路径。 当我使用 Linux 时,一切正常。但是在 Windows 上,我有一个小问题。 在我的代码中的某个时刻,我必须编
我想将大约 250 张图像及其文件名插入到 docx 文件中。 我的test.py文件: from pathlib import Path import docx from docx.shared i
我使用pip安装了spacy,然后使用下载了英文模型 $ python -m spacy 下载 en下载后给了我消息 您现在可以通过 spacy.load('en') 加载模型 使用 IPython,
这个问题在这里已经有了答案: Getting a typeError error in django project (3 个回答) 12 个月前关闭。 每当我运行服务器或在终端中执行任何命令时,都会
我编写了一个简单的序列化函数来存储文件树表示(基于复合模式...),但总是出现以下错误: java.io.NotSerializableException: sun.nio.fs.Wi
我正在跟进一个 django 教程,我刚刚使用 pip install django=2.1 安装了 django,它已成功安装,然后我使用 django-admin startproject App
你好, 我想打开目录中具有特定名称的 pdf 文件。这些文件名是从第二列中的 csv 文件输入中提供的。 我尝试了下面的代码,但是我收到了一条错误信息: TypeError: argument of
您好,我是 python 和 django 的新手,我正在练习 django,但是当我命令 python manage.py makemigration 和 python manage.py migr
我是 Pytest 的新手,一般都在开发。我正在尝试运行一个简单的 pytest 断言,但是收到错误: KeyError: WindowsPath('D:/ireact-tester-if/Lib/s
我是一名优秀的程序员,十分优秀!