python - 循环 Path.glob() (Pathlib) 的结果

标签 python glob pathlib

<分区>

我正在努力处理 Python 3.6 中 Pathlib 模块的 Path.glob() 方法的结果。

from pathlib import Path

dir = Path.cwd()

files = dir.glob('*.txt')
print(list(files))
>> [WindowsPath('C:/whatever/file1.txt'), WindowsPath('C:/whatever/file2.txt')]

for file in files:
    print(file)
    print('Check.')
>>

显然,glob 找到了文件,但是没有执行 for 循环。如何遍历 pathlib-glob-search 的结果?

最佳答案

>>> from pathlib import Path
>>> 
>>> _dir = Path.cwd()
>>> 
>>> files = _dir.glob('*.txt')
>>> 
>>> type(files)
<class 'generator'>

这里,files是一个generator,只能读取一次,然后就耗尽了。因此,当您尝试第二次阅读它时,您将无法阅读。

>>> for i in files:
...     print(i)
... 
/home/ahsanul/test/hello1.txt
/home/ahsanul/test/hello2.txt
/home/ahsanul/test/hello3.txt
/home/ahsanul/test/b.txt
>>> # let's loop though for the 2nd time
... 
>>> for i in files:
...     print(i)
... 
>>> 

关于python - 循环 Path.glob() (Pathlib) 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42246819/

相关文章:

python - 带有 if 语句的 glob 来选择要将哪些文件存储到变量?

python - 将相同形状的动态图像读取到Python NumPy数组中

unit-testing - 为磁盘上的文件对生成单元测试

python-3.x - python : move a file up one directory

python - 在 django 中获取基于时间的模型统计信息

python - Jupyter 是否支持 'read-only' 笔记本?

python - 合并由coverage.py生成的两个不同框架的html覆盖率报告

python - 如何在没有系统特定的情况下获得 pathlib 的 unix 路径处理好东西,例如 Path.resolve() changes/tmp to/private/tmp

python - 使用 pathlib 创建符号链接(symbolic link)

python - NumPy - 根据结构化数组中的其他值设置结构化数组中的值