Python - How to loop through lines of multiple files












0















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


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


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]


The print statement here prints all the values within a



Can someone help me with a possible explanation?










share|improve this question




















  • 1





    A similar question is answered over here

    – Half Genius
    Aug 2 '16 at 11:11






  • 1





    Also see stackoverflow.com/questions/13137969/…

    – PM 2Ring
    Aug 2 '16 at 11:17











  • I ended up using the "with" instead of the normal "open" statement which seems to work fine.

    – ifreak
    Aug 2 '16 at 13:31
















0















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


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


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]


The print statement here prints all the values within a



Can someone help me with a possible explanation?










share|improve this question




















  • 1





    A similar question is answered over here

    – Half Genius
    Aug 2 '16 at 11:11






  • 1





    Also see stackoverflow.com/questions/13137969/…

    – PM 2Ring
    Aug 2 '16 at 11:17











  • I ended up using the "with" instead of the normal "open" statement which seems to work fine.

    – ifreak
    Aug 2 '16 at 13:31














0












0








0








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


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


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]


The print statement here prints all the values within a



Can someone help me with a possible explanation?










share|improve this question
















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


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


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]


The print statement here prints all the values within a



Can someone help me with a possible explanation?







python file






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 2 '16 at 11:52









Half Genius

458621




458621










asked Aug 2 '16 at 11:05









ifreakifreak

69921436




69921436








  • 1





    A similar question is answered over here

    – Half Genius
    Aug 2 '16 at 11:11






  • 1





    Also see stackoverflow.com/questions/13137969/…

    – PM 2Ring
    Aug 2 '16 at 11:17











  • I ended up using the "with" instead of the normal "open" statement which seems to work fine.

    – ifreak
    Aug 2 '16 at 13:31














  • 1





    A similar question is answered over here

    – Half Genius
    Aug 2 '16 at 11:11






  • 1





    Also see stackoverflow.com/questions/13137969/…

    – PM 2Ring
    Aug 2 '16 at 11:17











  • I ended up using the "with" instead of the normal "open" statement which seems to work fine.

    – ifreak
    Aug 2 '16 at 13:31








1




1





A similar question is answered over here

– Half Genius
Aug 2 '16 at 11:11





A similar question is answered over here

– Half Genius
Aug 2 '16 at 11:11




1




1





Also see stackoverflow.com/questions/13137969/…

– PM 2Ring
Aug 2 '16 at 11:17





Also see stackoverflow.com/questions/13137969/…

– PM 2Ring
Aug 2 '16 at 11:17













I ended up using the "with" instead of the normal "open" statement which seems to work fine.

– ifreak
Aug 2 '16 at 13:31





I ended up using the "with" instead of the normal "open" statement which seems to work fine.

– ifreak
Aug 2 '16 at 13:31












4 Answers
4






active

oldest

votes


















4














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.



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





share|improve this answer































    3














    You can fetch b to a list of lines with readlines(), and then you can iterate over it again and again:



    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





    share|improve this answer





















    • 2





      Depending on the size it is even better to read the lines of b once and for all

      – Jean-François Fabre
      Aug 2 '16 at 11:14



















    1














    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





    share|improve this answer

































      0














      Convert b as a list else first iteration through b will consume the file.



       blist= list(b)


      Then the inner loop



      For bl in blist:
      ...





      share|improve this answer
























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f38718714%2fpython-how-to-loop-through-lines-of-multiple-files%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        4














        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.



        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





        share|improve this answer




























          4














          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.



          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





          share|improve this answer


























            4












            4








            4







            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.



            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





            share|improve this answer













            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.



            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






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Aug 2 '16 at 11:10









            moopetmoopet

            4,51812333




            4,51812333

























                3














                You can fetch b to a list of lines with readlines(), and then you can iterate over it again and again:



                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





                share|improve this answer





















                • 2





                  Depending on the size it is even better to read the lines of b once and for all

                  – Jean-François Fabre
                  Aug 2 '16 at 11:14
















                3














                You can fetch b to a list of lines with readlines(), and then you can iterate over it again and again:



                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





                share|improve this answer





















                • 2





                  Depending on the size it is even better to read the lines of b once and for all

                  – Jean-François Fabre
                  Aug 2 '16 at 11:14














                3












                3








                3







                You can fetch b to a list of lines with readlines(), and then you can iterate over it again and again:



                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





                share|improve this answer















                You can fetch b to a list of lines with readlines(), and then you can iterate over it again and again:



                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






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Aug 2 '16 at 11:15

























                answered Aug 2 '16 at 11:08









                Ohad EytanOhad Eytan

                5,0471627




                5,0471627








                • 2





                  Depending on the size it is even better to read the lines of b once and for all

                  – Jean-François Fabre
                  Aug 2 '16 at 11:14














                • 2





                  Depending on the size it is even better to read the lines of b once and for all

                  – Jean-François Fabre
                  Aug 2 '16 at 11:14








                2




                2





                Depending on the size it is even better to read the lines of b once and for all

                – Jean-François Fabre
                Aug 2 '16 at 11:14





                Depending on the size it is even better to read the lines of b once and for all

                – Jean-François Fabre
                Aug 2 '16 at 11:14











                1














                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





                share|improve this answer






























                  1














                  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





                  share|improve this answer




























                    1












                    1








                    1







                    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





                    share|improve this answer















                    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






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Mar 8 at 4:58

























                    answered Aug 2 '16 at 11:14









                    VaibhavVaibhav

                    669416




                    669416























                        0














                        Convert b as a list else first iteration through b will consume the file.



                         blist= list(b)


                        Then the inner loop



                        For bl in blist:
                        ...





                        share|improve this answer




























                          0














                          Convert b as a list else first iteration through b will consume the file.



                           blist= list(b)


                          Then the inner loop



                          For bl in blist:
                          ...





                          share|improve this answer


























                            0












                            0








                            0







                            Convert b as a list else first iteration through b will consume the file.



                             blist= list(b)


                            Then the inner loop



                            For bl in blist:
                            ...





                            share|improve this answer













                            Convert b as a list else first iteration through b will consume the file.



                             blist= list(b)


                            Then the inner loop



                            For bl in blist:
                            ...






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Aug 2 '16 at 11:09









                            Jean-François FabreJean-François Fabre

                            106k1057115




                            106k1057115






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f38718714%2fpython-how-to-loop-through-lines-of-multiple-files%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                MongoDB - Not Authorized To Execute Command

                                Npm cannot find a required file even through it is in the searched directory

                                in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith