简体   繁体   English

Python Pathlib 异常行为

[英]Python Pathlib Strange Behaviour

I can find all the files in the subfolders of a folder path with specific filetypes in this way:我可以通过这种方式找到具有特定文件类型的文件夹路径的子文件夹中的所有文件:

list(Path(folder_path).glob('**/*.[jpg][jpeg][png]*'))

But if I change the code to try and find other filetypes (like jfif or bmp ), with some filetypes the code works and with the others, it can't find the filepaths:但是,如果我更改代码以尝试查找其他文件类型(如jfifbmp ),对于某些文件类型,代码可以工作,而对于其他文件类型,它找不到文件路径:

list(Path(folder_path).glob('**/*.[jpg][jpeg][jfif][png]*'))

Why isn't this code working properly?为什么这段代码不能正常工作?

According to the pathlib docs , the pattern syntax is the same as for fnmatch .根据pathlib 文档,模式语法与fnmatch相同。 A pattern like [jpg] matches a single character, which is either a j , a p or a g .[jpg]这样的模式匹配单个字符,可以是jpg I don't think this type of pattern can handle alternatives — you have to use some other mechanism for filtering;我不认为这种类型的模式可以处理替代方案——你必须使用一些其他的过滤机制; something like foo.suffix in [...] or a regexp.类似于foo.suffix in [...]或正则表达式。

Regex style "solution":正则表达式样式“解决方案”:

from pathlib import Path
from re import search, IGNORECASE

folder_path = "."
images = r".*\.(jpg|jpeg|jfif|png)$"

files = list(filter(lambda f: search(images, str(f)), Path(folder_path).rglob("*")))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM