【问题标题】:Search for Filename and Parent Folder Using Regex - Python使用正则表达式搜索文件名和父文件夹 - Python
【发布时间】:2022-01-14 16:37:00
【问题描述】:

我正在尝试使用正则表达式库确认文件的文件名和父文件夹,而不必明确列出文件路径,但遇到了问题。我想打印文件的名称以及文件的父文件夹,这是我的脚本:

import re
import glob
from pathlib import Path

files = [f for f in glob.glob('*.tif') if re.search('((?i)\/Image_Names\/.*_dsm.*\.tif)', f)]

for filename in files:
    print(files)  # list the files
    print(Path().resolve().parts[-2])  # list the parent folder from where the .tif file resides

我可以使用 Path 函数将父文件夹列出到 .tif,但不能列出文件名本身。我需要能够通过正则表达式显式打印文件名(_dsm.tif)和父文件夹(Image_Names),非常感谢任何帮助!

【问题讨论】:

    标签: python regex directory path filenames


    【解决方案1】:

    你可以使用

    files = [re.search(r'(?i)(Image_Names)/(.*_dsm.*\.tif)', f).groups() for f in glob.glob('*.tif') if re.search('(?i)Image_Names/.*_dsm.*\.tif', f)]
    

    输出将类似于[('Image_Names', 'xxxx_dsm.tif'), ('Image_Names', 'bbbb_dsm_blah.tif')]

    【讨论】:

      猜你喜欢
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多