Python-如何遍历多个文件的行 [英] Python - How to loop through lines of multiple files

查看:101
本文介绍了Python-如何遍历多个文件的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个文件:"a.txt""b.txt",我要在它们之间匹配行.这些文件包含以下内容:

I have 2 files: "a.txt" and "b.txt" where I want to match lines between them. 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

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

Surprisingly, the print statement ONLY prints the following:

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

这似乎是a上的循环仅被访问了一次.我尝试调试的内容如下:

Which appears to be that the loop on a is only accessed once. 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]

此处的print语句将打印a

The print statement here prints all the values within a

有人可以帮我一个可能的解释吗?

Can someone help me with a possible explanation?

推荐答案

每次尝试遍历b.txt时,都需要将文件指针重置为b.txt的文件开头

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.

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

The easiest way to do this is with file.seek(0) as shown below:

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

这篇关于Python-如何遍历多个文件的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆