【问题标题】:Concatenate all files that map values in the same key连接在同一键中映射值的所有文件
【发布时间】:2021-01-27 02:48:42
【问题描述】:

我有一个分类不同模式的字典:

dico_cluster={'cluster_1': ['CUX2', 'CUX1'], 'cluster_2': ['RFX3', 'RFX2'],'cluster_3': ['REST']}

然后我在文件夹中有文件:

"/path/to/test/files/CUX1.txt"
"/path/to/test/files/CUX2.txt"
"/path/to/test/files/RFX3.txt"
"/path/to/test/files/RFX2.txt"
"/path/to/test/files/REST.txt"
"/path/to/test/files/ZEB.txt"
"/path/to/test/files/TEST.txt"

我正在尝试连接同一集群中的文件。输出文件名应该是模式连接的名称,下划线“_”

我试过这个:

filenames = glob.glob('/path/to/test/files/*.txt')

for clee in dico_cluster.keys():
    fname='_'.join(dico_cluster[clee])
    outfilename ='/path/to/test/outfiles/'+ fname + ".txt"
    for file in filenames:
        tf_file=file.split('/')[-1].split('.')[0]
        if tf_file in dico_cluster[clee]:
            with open(outfilename, 'wb') as outfile:
                for filename in filenames:
                    if filename == outfilename:
            # don't want to copy the output into the output
                        continue
                    with open(filename, 'rb') as readfile:
                        shutil.copyfileobj(readfile, outfile) 

但它不起作用。我只是连接所有文件。 我想 cat 同一个集群中的文件。

【问题讨论】:

    标签: python dictionary concatenation


    【解决方案1】:

    我会推荐使用 os 包,它更容易使用。

    如果我理解您的问题,我会尝试通过在编写文件之前加载文件的全部内容来做到这一点。

    import os
    for clee in dico_cluster.keys():
            my_clusters =list(set(dico_cluster[clee]))
            fname = "_".join(my_clusters)
            data = list()
            outfilename = os.path.join("/path/to/test/outfiles", fname + ".txt")
            for file in filenames:
                tmp_dict = dict()
                tf_file = os.path.basename(file).split(".")[0]
                if tf_file in my_clusters:
                    with open(file, 'rb') as f1:
                        data.extend([elm for elm in f1.readlines()])
    
            with open(outfilename, "wb") as _output_file:
                for elm in data:
                    _output_file.write(elm)
    
    
        
    

    【讨论】:

      猜你喜欢
      • 2019-11-16
      • 2019-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 2012-06-17
      • 2020-05-13
      • 1970-01-01
      相关资源
      最近更新 更多