简体   繁体   English

Python-如何遍历多个文件的行

[英]Python - How to loop through lines of multiple files

I have 2 files: "a.txt" and "b.txt" where I want to match lines between them. 我有2个文件: "a.txt""b.txt" ,我要在它们之间进行匹配。 The files contain the following: 这些文件包含以下内容:

1
2
3
4
5
6
7
8
9
10

To match the lines, I'm doing the following 为了匹配这些行,我正在执行以下操作

    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

Surprisingly, the print statement ONLY prints the following: 令人惊讶的是,print语句ONLY打印以下内容:

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

Which appears to be that the loop on a is only accessed once. 这似乎是a上的循环只能访问一次。 What I tried for debugging is the following: 我尝试调试的内容如下:

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]

The print statement here prints all the values within a 此处的print语句会打印a

Can someone help me with a possible explanation? 有人可以帮我一个可能的解释吗?

You need to reset the file pointer to the start of the file for b.txt each time you attempt to loop through it, otherwise you've reached the end. 每次尝试遍历文件时,都需要将文件指针重置为b.txt的文件b.txt ,否则将到达末尾。

The easiest way to do this is with file.seek(0) as shown below: 最简单的方法是使用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

You can fetch b to a list of lines with readlines() , and then you can iterate over it again and again: 您可以使用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

try this : 尝试这个 :

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])

Explanation: 说明:

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

Convert b as a list else first iteration through b will consume the file. 将b转换为列表,否则通过b的第一次迭代将消耗该文件。

 blist= list(b)

Then the inner loop 然后是内循环

For bl in blist:
 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM