Python-如何在多个文件的行中循环



我有两个文件:"a.txt""b.txt",我想在它们之间匹配行。文件包含以下内容:

1
2
3
4
5
6
7
8
9
10

为了匹配线路,我正在进行以下

    a = open("a.txt","r") 
    b = open("b.txt","r")
    for al in a:
        al = al.split()
        val_a = al[0]
        for bl in b:
            bl = bl.split()
            val_b = bl[0]
            print val_a, val_b

令人惊讶的是,打印语句ONLY打印了以下内容:

1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10

这似乎是上的循环只访问一次。我尝试调试的内容如下:

for al in a:
    al = al.split()
    val_a = al[0]
    print val_a
    for bl in b:
        bl = bl.split()
        val_b = bl[0]

此处的print语句打印a 中的所有值

有人能帮我解释一下吗?

每次尝试循环遍历b.txt时,都需要将文件指针重置为文件的开头,否则就到达了末尾。

最简单的方法是使用file.seek(0),如下所示:

a = open("a.txt","r") 
b = open("b.txt","r")
for al in a:
    al = al.split()
    val_a = al[0]
    b.seek(0)
    for bl in b:
        bl = bl.split()
        val_b = bl[0]
        print val_a, val_b

您可以使用readlines()b提取到一个行列表中,然后您可以一次又一次地迭代它:

a = open("a.txt","r") 
b = open("b.txt","r").readlines()
for al in a:
    al = al.split()
    val_a = al[0]
    for bl in b:
        bl = bl.split()
        val_b = bl[0]
        print val_a, val_b

试试这个:

a = open("a.txt","r")
b = open("b.txt","r")
for i,j in zip(a,b):
    print (i.split()[0])
    print (j.split()[0])

说明:

1)zip file will open both files simultanously
2)for loop will loop through line by line (i=one line in a-file, j=one line in b-file)
3)i.split()[0] will give first word/element of line

将b转换为列表,否则通过b的第一次迭代将使用该文件。

 blist= list(b)

然后内环

For bl in blist:
 ...

相关内容

  • 没有找到相关文章

最新更新