Skip to main content
 首页 » 编程设计

python之通过循环比较 2 个 .csv 文件

2024年10月01日10cloudgamer

我有 15 个 .csv 文件,格式如下:

**File 1** 
MYC 
RASSF1 
DAPK1 
MDM2 
TP53 
E2F1 
... 
 
**File 2** 
K06227 
C00187 
GLI1 
PTCH1 
BMP2 
TP53 
... 

我想创建一个循环,遍历 15 个文件中的每一个,并每次比较 2 个文件,从而创建唯一的对。因此,File 1 和 File 2 将相互比较,给出一个输出告诉我它找到了多少匹配项以及它们是什么。所以在上面的例子中,输出将是:

1 match and TP53 

循环将用于比较所有文件,因此 1,3(File 1 与 File 3),1,4 等等。

f1 = set(open(str(cancers[1]) + '.csv', 'r')) 
f2 = set(open(str(cancers[2]) + '.csv', 'r')) 
f3 = open(str(cancers[1]) + '_vs_' + str(cancers[2]) + '.txt', 'wb').writelines(f1 & f2) 

上面的方法有效,但我很难创建循环部分。

请您参考如下方法:

为了不比较同一个文件,也为了让代码灵活适应癌症的数量,我会这样编码。我假设 cancer 是一个列表。

# example list of cancers 
cancers = ['BRCA', 'BLCA', 'HNSC'] 
fout = open('match.csv', 'w') 
for i in range(len(cancers)): 
    for j in range(len(cancers)): 
        if j > i: 
            # if there are string elements in cancers, 
            # then it doesn't need 'str(cancers[i])' 
            f1 = [x.strip() for x in set(open(cancers[i] + '.csv', 'r'))] 
            f2 = [x.strip() for x in set(open(cancers[j] + '.csv', 'r'))] 
            match = list(set(f1) & set(f2)) 
            # I use ; to separate matched genes to make excel able to read 
            fout.write('{}_vs_{},{} matches,{}\n'.format( 
                cancers[i], cancers[j], len(match), ';'.join(match))) 
fout.close() 

结果

BRCA_vs_BLCA,1 matches,TP53 
BRCA_vs_HNSC,6 matches,TP53;BMP2;GLI1;C00187;PTCH1;K06227 
BLCA_vs_HNSC,1 matches,TP53