代码之家  ›  专栏  ›  技术社区  ›  nmr

python中基于子字符串的文件名变量捕获

  •  0
  • nmr  · 技术社区  · 6 月前

    我有一个下面的场景 python 。我想检查当前工作目录和该目录中存在的文件,并创建一个变量。

    我做了如下操作

    import os
    
    # current working directory
    print(os.getcwd())
    
    # files present in that directory
    dir_contents = os.listdir('.')
    
    
    # below is the output of the dir_contents
    
    print(dir_contents)
    ['.test.json.crc', '.wf_list_dir_param.py.crc', 'test.json', 'wf_list_dir_param.py']
    

    现在从 dir_contents 我想提取的列表 wf_list_dir 作为一个变量。

    我需要在下面做

    1. 找出以开头的元素 wf 以结束 param.py
    2. 提取之前的所有内容 _param.py 作为一个变量

    我该怎么做?

    2 回复  |  直到 6 月前
        1
  •  3
  •   SIGHUP    6 月前

    您可以使用pathlib实现这一点。Path.glob如下:

    from pathlib import Path
    
    prefix = "wf"
    suffix = "_param.py"
    source_dir = Path(".")
    
    for file in source_dir.glob(f"{prefix}*{suffix}"):
        print(file.name[:-len(suffix)])
    

    因此,如果您当前的工作目录包含一个名为wf_list_dir_param.py的文件,则会发出wf_list-dir

        2
  •  1
  •   JonSG    6 月前

    我认为最简单的方法是使用 re 模块,但您也可以考虑使用 str.startswith() str.endswith() 作为一个起点。

    不管怎样,给定文件列表,您可以使用正则表达式模式,如 r"^wf_(.+)_param\.py$" 识别匹配项并挑选出您想要的部分。

    也许像:

    import re
    
    filenames = [".test.json.crc", ".wf_list_dir_param.py.crc", "test.json", "wf_list_dir_param.py"]
    pattern = re.compile(r"^wf_(.+)_param\.py$")
    for text in filenames:
        match = pattern.search(text)
        if match:
            print(match.group(1))   
    

    这应该给你:

    list_dir
    

    更多关于regex101.com的模式

    ^      asserts position at start of a line
    wf_    matches the characters wf_ literally (case sensitive)
    1st Capturing Group (.+)
           . matches any character (except for line terminators)
           + matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
    _param matches the characters _param literally (case sensitive)
    \.     matches the character . with index 4610 (2E16 or 568) literally (case sensitive)
    py     matches the characters py literally (case sensitive)
    $      asserts position at the end of a line
    

    如果你真的想要“ wf_ “作为结果的一部分,您可以将其移动到您的捕获中。

    pattern = re.compile(r"^(wf_.+)_param\.py$")
    

    有了这个更新的模式,原始代码应该会给你:

    wf_list_dir