搜索带有部分名称的文件并添加到字典中

时间:2019-04-05 18:49:07

标签: python dictionary os.walk

您好,我所有的文件都保存在某个目录中。

dir ="/user/raw/samples"

我需要将所有以特定字符串结尾的文件放入字典dic_x中,将其他文件放入字典dic_z中。

以下是dir中的文件名:

SAP_XCV_1980_H7LYVDRXX_2_ALPH_C_cR_c1_v1_0_FCDSSA_DDDD_S14_L002_R1_001_MM_1.fz.gz
SAP_XCV_1980_H7LYVDRXX_2_ALPH_C_cR_c1_v1_0_FCDSSA_DDDD_S14_L002_R2_001_MM_1.fz.gz
SAP_XCV_1980_H7LYVDRXX_2_ALPH_C_cR_c1_v1_0_FCDSSA_DDDD_S14_L001_R2_001_MM_1.fz.gz
SAP_XCV_1980_H7LYVDRXX_2_ALPH_C_cR_c1_v1_0_FCDSSA_DDDD_S14_L001_R1_001_MM_1.fz.gz

我有两个字典

 import sys
import os
import subprocess
import glob
import fnmatch
import re
    listF = ['ALPH']
    FH_sample = listF
    dic_x = {}
    dic_z = {}

    for line in FH_sample:
        dic_x[line.strip().split('\n')[0]] =[]
        dic_z[line.strip().split('\n')[0]] =[]

        for root, sub, file in os.walk(dir):
            for name in file:
                if name.endswith(".fz.gz"):
                    m1 = re.search('(.*)_R1', file)
                    m2 = re.search('(.*)_R2', file)
                if m1 and m1.group(1) in dic_x:
                    dic_x[m1.group(1)].append(file)
                if m2 and m2.group(1) in dic_z:
                    dic_z[m2.group(1)].append(file)

但是,我无法使用上述代码行来获取字典中的所有值。我需要像下面这样的词典,

dic_x = {'ALPH': ['SAP_XCV_1980_H7LYVDRXX_2_ALPH_C_cR_c1_v1_0_FCDSSA_DDDD_S14_L001_R1_001_MM_1.fz.gz','SAP_XCV_1980_H7LYVDRXX_2_ALPH_C_cR_c1_v1_0_FCDSSA_DDDD_S14_L002_R1_001_MM_1.fz.gz']}

dic_z = {'ALPH': ['SAP_XCV_1980_H7LYVDRXX_2_ALPH_C_cR_c1_v1_0_FCDSSA_DDDD_S14_L001_R2_001_MM_1.fz.gz','SAP_XCV_1980_H7LYVDRXX_2_ALPH_C_cR_c1_v1_0_FCDSSA_DDDD_S14_L002_R2_001_MM_1.fz.gz']}

当前dic_xdic_z看起来像这样,

dic_z = {'ALPH': []}
dic_x = {'ALPH': []}

1 个答案:

答案 0 :(得分:1)

您可以使用列表

import os
import fnmatch
path = "test_images/"
x_list = ([f for f in os.listdir(path) if fnmatch.fnmatch(f, "*.png")])
z_list= ([f for f in os.listdir(path) if fnmatch.fnmatch(f, "*.bmp")])
dic_x = {'ALPH' : x_list }
dic_z = {'ALPH': z_list}

根据您的情况,您可以将*.png替换为*R1_001_MM_1.fz.gz,将*.bmp替换为*R2_001_MM_1.fz.gz'。另外test_images//user/raw/samples/