Python:for循环中的循环不符合预期

Har*_*pal 0 python

我使用以下代码来组合两个文本文件:

def combine_acpd_ccs(self, ccs_file, acps_file, out_file):

    with open(ccs_file, 'r') as in_file1:
        with open(acps_file, 'r') as in_file2:
            with open(out_file, 'w') as out1:
                out1.write('PDB\tPA\tEHSS\tACPS\n')
                for line in in_file1:
                    segs = line.split()
                    for i in in_file2:
                        sse_score = i.split()
                        #print line
                        #print segs
                        if segs[0][:-4] == sse_score[0]:
                            out1.write(segs[0][:-4]+'\t'+segs[1]+'\t'+segs[2]+'\t'+sse_score[1]+'\n')
Run Code Online (Sandbox Code Playgroud)

示例数据如下所示:

ccs_file:

1b0o.pdb    1399.0  1772.0
1b8e.pdb    1397.0  1764.0
Run Code Online (Sandbox Code Playgroud)

acps_file:

1b0o    0.000756946316066
1b8e    8.40662008775
1b0o    6.25931529116
Run Code Online (Sandbox Code Playgroud)

我期待我的表现如下:

PDB PA  EHSS    ACPS
1b0o    1399.0  1772.0  0.000756946316066
1b0o    1399.0  1772.0  6.25931529116
1b8e    1397.0  1764.0 8.40662008775
Run Code Online (Sandbox Code Playgroud)

但是我的代码只生成了我预期输出的前两行.如果我segs在第二个for循环中打印,则只将第一行ccs_file传入循环.我出错的任何想法?

NPE*_*NPE 7

问题是in_file2在外循环的每次迭代后都不会重新打开/倒回.

执行了

for i in in_file2:
Run Code Online (Sandbox Code Playgroud)

所有后续的迭代尝试in_file2都不会做任何事情,因为文件指针已经位于文件的末尾.

如果文件相对较小,您可能需要加载ccs_file到内存中,并且只进行字典查找.