鱼C论坛

 找回密码
 立即注册
查看: 3311|回复: 2

[已解决]Python的pathlib模块结合正则一起用吗

[复制链接]
发表于 2021-4-20 15:20:37 | 显示全部楼层 |阅读模式
10鱼币
比如说我想在glob和rglob使用正则查找文件是否可行
  1. from pathlib import Path

  2. for file in Path().glob('\d+.txt'):
  3.     print(file.name)
复制代码

类似这样
最佳答案
2021-4-20 15:20:38
本帖最后由 阿奇_o 于 2021-4-20 17:53 编辑

官方文档里,似乎没说可以用正则,一般用法是:
  1. from pathlib import Path
  2. p = Path('.') #生成当前目录的Path对象(os.path的高一级的封装)

  3. #列出当前目录包含哪些子目录
  4. [x for x in p.iterdir() if x.is_dir()]

  5. #列出该目录下的所有 .py文件 (包括子目录里的)
  6. #The “**” pattern means “this directory and all subdirectories, recursively”. In other words, it enables recursive globbing:
  7. list(p.glob('**/*.py')) # '**' 代表递归查找所有子目录

  8. # 而 rglob() 怎么用?
  9. list(p.rglob("*.py")) # 等价于与 glob('**/*.py')
  10. # This is like calling Path.glob() with “**/” added in front of the given relative pattern:
  11. # 即 rglob的 r表示递归,而不是 正则

复制代码

通常更多的应该是用 os.path 和 os.listdir 等方法,更“底层点”,也更直接些。

最佳答案

查看完整内容

官方文档里,似乎没说可以用正则,一般用法是: 通常更多的应该是用 os.path 和 os.listdir 等方法,更“底层点”,也更直接些。

本帖被以下淘专辑推荐:

  • · python|主题: 62, 订阅: 4
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-4-20 15:20:38 | 显示全部楼层    本楼为最佳答案   
本帖最后由 阿奇_o 于 2021-4-20 17:53 编辑

官方文档里,似乎没说可以用正则,一般用法是:
  1. from pathlib import Path
  2. p = Path('.') #生成当前目录的Path对象(os.path的高一级的封装)

  3. #列出当前目录包含哪些子目录
  4. [x for x in p.iterdir() if x.is_dir()]

  5. #列出该目录下的所有 .py文件 (包括子目录里的)
  6. #The “**” pattern means “this directory and all subdirectories, recursively”. In other words, it enables recursive globbing:
  7. list(p.glob('**/*.py')) # '**' 代表递归查找所有子目录

  8. # 而 rglob() 怎么用?
  9. list(p.rglob("*.py")) # 等价于与 glob('**/*.py')
  10. # This is like calling Path.glob() with “**/” added in front of the given relative pattern:
  11. # 即 rglob的 r表示递归,而不是 正则

复制代码

通常更多的应该是用 os.path 和 os.listdir 等方法,更“底层点”,也更直接些。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-5-13 05:42:33 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-19 21:54

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表