How to read one line down from text file in python





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







2















I have a txt file with the following line:



ENBO => [
'h4d gh34245 ran54'
]


I want to be able to put the containments h4d gh34245 ran54 inside a variable in my python script.



My python script:



f = open(txt.txt, "r")

for line1 in f:
if ("ENBO" in line1):
print (line1)


However this just prints ENBO => [ , but I want a way to read the line below my current line ENBO => [ to get the line h4d gh34245 ran54 and store it inside of a variable in my script so I may read from it accordingly. Also, I do not want to change the txt file in anyway. And I want to search for the containments of ENBO specifically, not hard-code search for h4d gh34245 ran54










share|improve this question





























    2















    I have a txt file with the following line:



    ENBO => [
    'h4d gh34245 ran54'
    ]


    I want to be able to put the containments h4d gh34245 ran54 inside a variable in my python script.



    My python script:



    f = open(txt.txt, "r")

    for line1 in f:
    if ("ENBO" in line1):
    print (line1)


    However this just prints ENBO => [ , but I want a way to read the line below my current line ENBO => [ to get the line h4d gh34245 ran54 and store it inside of a variable in my script so I may read from it accordingly. Also, I do not want to change the txt file in anyway. And I want to search for the containments of ENBO specifically, not hard-code search for h4d gh34245 ran54










    share|improve this question

























      2












      2








      2








      I have a txt file with the following line:



      ENBO => [
      'h4d gh34245 ran54'
      ]


      I want to be able to put the containments h4d gh34245 ran54 inside a variable in my python script.



      My python script:



      f = open(txt.txt, "r")

      for line1 in f:
      if ("ENBO" in line1):
      print (line1)


      However this just prints ENBO => [ , but I want a way to read the line below my current line ENBO => [ to get the line h4d gh34245 ran54 and store it inside of a variable in my script so I may read from it accordingly. Also, I do not want to change the txt file in anyway. And I want to search for the containments of ENBO specifically, not hard-code search for h4d gh34245 ran54










      share|improve this question














      I have a txt file with the following line:



      ENBO => [
      'h4d gh34245 ran54'
      ]


      I want to be able to put the containments h4d gh34245 ran54 inside a variable in my python script.



      My python script:



      f = open(txt.txt, "r")

      for line1 in f:
      if ("ENBO" in line1):
      print (line1)


      However this just prints ENBO => [ , but I want a way to read the line below my current line ENBO => [ to get the line h4d gh34245 ran54 and store it inside of a variable in my script so I may read from it accordingly. Also, I do not want to change the txt file in anyway. And I want to search for the containments of ENBO specifically, not hard-code search for h4d gh34245 ran54







      python file






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 16 '18 at 21:31









      FranceMadridFranceMadrid

      327




      327
























          7 Answers
          7






          active

          oldest

          votes


















          1














          Use a context manager to loop over the file and print/store the next value if a line of interest is found:



          with open('txt.txt', "r") as f:
          for line in f:
          if 'ENBO' in line:
          print(next(f)) #you can also append the values to a list here
          else:
          #do something here*
          pass

          >>'h4d gh34245 ran54'

          'h4d gh34245 ran54'

          'h4d gh34245 ran54'

          'h4d gh34245 ran54'


          You can do this because f is a generator, it prints the next line if ENBO and continues after the next line.



          This is tested in a mock text file:



          ENBO => [
          'h4d gh34245 ran54'
          ]

          ENBO => [
          'h4d gh34245 ran54'
          ]

          ENBO => [
          'h4d gh34245 ran54'
          ]

          ENBO => [
          'h4d gh34245 ran54'
          ]





          share|improve this answer
























          • Yes!!! this did it. Thank you!

            – FranceMadrid
            Nov 16 '18 at 21:46











          • Happy to help, just pay attention to the criteria in the for loop, in this case only ENBO is extracted. There are also very similar examples in the Python documentation here

            – BernardL
            Nov 16 '18 at 21:49





















          0














          Something like this should work.



          print_next_line = False
          for line1 in f:
          if print_next_line:
          print(line1)
          print_next_line = False
          if "ENBO" in line1:
          print_next_line = True





          share|improve this answer
























          • This just prints out nothing for me :/. I also added print (line1) to end of last if statement

            – FranceMadrid
            Nov 16 '18 at 21:38





















          0














          The answer yper gave should work, but may I also suggest looking into JSON file formatting? This would allow you to assign a value to the key "ENBO" and then access that through a key:value pairing?



          Not sure what you're reading the file for, or what generates it so can't guarantee that this approach would help you.






          share|improve this answer































            0














            Do you mean that you wish to put the contents of a text file into a variable?
            There are two ways you would do this, the first of which is just to put it all into one string (with only one line I think this is what you want):



            f = open(txt.txt, "r") # opening the file

            output = f.read().replace('n', '') # replacing the newline with spaces


            You can just remove a bit of the second line to put it into an array of the lines.



            output = f.read()





            share|improve this answer































              0














              The usual way I approach something like this is to read until I find the line that signals the start of the data I'm looking for, then gather the desired data. For this question, something like the following should work:



              f = open('txt.txt', "r")
              for line1 in f:
              if ("ENBO" in line1):
              break # Stops the loop
              if f: # Make sure you didn't hit the end of the file
              data_line = f.readline() # Grab the next line
              print(data_line)





              share|improve this answer































                0














                I would recommend just doing this:



                from pathlib import Path

                print(Path(MY_FILE).read_text().splitlines()[1])


                Using pathlib for your file operations is highly recommended. If you can't/won't use it, this is equivalent:



                with open(MY_FILE) as f:
                print(f.readlines()[1])





                share|improve this answer































                  0














                  First of all, it is important to note that your file contains 3 lines, even if semantically those 3 lines represent only one entity.



                  Now, if your file is really this simple, and you really just want the second line, you can use the method readlines().
                  This will read the whole file and return a list, where each line of the file is represented by one item.



                  Then, if you know that your line is always on the second line (index 1), you can just access it directly.



                  here is the suggested solution:



                  f = open(txt.txt, "r")
                  all_lines = f.readlines()
                  requested_line = all_lines[1]


                  Also, I would like to suggest that you use the with syntax to open the file, so the resource is disposed of when it is no longer used:



                  with open(txt.txt, "r") as f:
                  all_lines = f.readlines()
                  requested_line = all_lines[1]


                  You can understand more about the with statement in the docs or in the developer's guide



                  Note that readlines() goes through the whole file, so if your file might be of an unknown length, you should probably refrain from using it.






                  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%2f53345693%2fhow-to-read-one-line-down-from-text-file-in-python%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown

























                    7 Answers
                    7






                    active

                    oldest

                    votes








                    7 Answers
                    7






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    1














                    Use a context manager to loop over the file and print/store the next value if a line of interest is found:



                    with open('txt.txt', "r") as f:
                    for line in f:
                    if 'ENBO' in line:
                    print(next(f)) #you can also append the values to a list here
                    else:
                    #do something here*
                    pass

                    >>'h4d gh34245 ran54'

                    'h4d gh34245 ran54'

                    'h4d gh34245 ran54'

                    'h4d gh34245 ran54'


                    You can do this because f is a generator, it prints the next line if ENBO and continues after the next line.



                    This is tested in a mock text file:



                    ENBO => [
                    'h4d gh34245 ran54'
                    ]

                    ENBO => [
                    'h4d gh34245 ran54'
                    ]

                    ENBO => [
                    'h4d gh34245 ran54'
                    ]

                    ENBO => [
                    'h4d gh34245 ran54'
                    ]





                    share|improve this answer
























                    • Yes!!! this did it. Thank you!

                      – FranceMadrid
                      Nov 16 '18 at 21:46











                    • Happy to help, just pay attention to the criteria in the for loop, in this case only ENBO is extracted. There are also very similar examples in the Python documentation here

                      – BernardL
                      Nov 16 '18 at 21:49


















                    1














                    Use a context manager to loop over the file and print/store the next value if a line of interest is found:



                    with open('txt.txt', "r") as f:
                    for line in f:
                    if 'ENBO' in line:
                    print(next(f)) #you can also append the values to a list here
                    else:
                    #do something here*
                    pass

                    >>'h4d gh34245 ran54'

                    'h4d gh34245 ran54'

                    'h4d gh34245 ran54'

                    'h4d gh34245 ran54'


                    You can do this because f is a generator, it prints the next line if ENBO and continues after the next line.



                    This is tested in a mock text file:



                    ENBO => [
                    'h4d gh34245 ran54'
                    ]

                    ENBO => [
                    'h4d gh34245 ran54'
                    ]

                    ENBO => [
                    'h4d gh34245 ran54'
                    ]

                    ENBO => [
                    'h4d gh34245 ran54'
                    ]





                    share|improve this answer
























                    • Yes!!! this did it. Thank you!

                      – FranceMadrid
                      Nov 16 '18 at 21:46











                    • Happy to help, just pay attention to the criteria in the for loop, in this case only ENBO is extracted. There are also very similar examples in the Python documentation here

                      – BernardL
                      Nov 16 '18 at 21:49
















                    1












                    1








                    1







                    Use a context manager to loop over the file and print/store the next value if a line of interest is found:



                    with open('txt.txt', "r") as f:
                    for line in f:
                    if 'ENBO' in line:
                    print(next(f)) #you can also append the values to a list here
                    else:
                    #do something here*
                    pass

                    >>'h4d gh34245 ran54'

                    'h4d gh34245 ran54'

                    'h4d gh34245 ran54'

                    'h4d gh34245 ran54'


                    You can do this because f is a generator, it prints the next line if ENBO and continues after the next line.



                    This is tested in a mock text file:



                    ENBO => [
                    'h4d gh34245 ran54'
                    ]

                    ENBO => [
                    'h4d gh34245 ran54'
                    ]

                    ENBO => [
                    'h4d gh34245 ran54'
                    ]

                    ENBO => [
                    'h4d gh34245 ran54'
                    ]





                    share|improve this answer













                    Use a context manager to loop over the file and print/store the next value if a line of interest is found:



                    with open('txt.txt', "r") as f:
                    for line in f:
                    if 'ENBO' in line:
                    print(next(f)) #you can also append the values to a list here
                    else:
                    #do something here*
                    pass

                    >>'h4d gh34245 ran54'

                    'h4d gh34245 ran54'

                    'h4d gh34245 ran54'

                    'h4d gh34245 ran54'


                    You can do this because f is a generator, it prints the next line if ENBO and continues after the next line.



                    This is tested in a mock text file:



                    ENBO => [
                    'h4d gh34245 ran54'
                    ]

                    ENBO => [
                    'h4d gh34245 ran54'
                    ]

                    ENBO => [
                    'h4d gh34245 ran54'
                    ]

                    ENBO => [
                    'h4d gh34245 ran54'
                    ]






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 16 '18 at 21:44









                    BernardLBernardL

                    2,42411232




                    2,42411232













                    • Yes!!! this did it. Thank you!

                      – FranceMadrid
                      Nov 16 '18 at 21:46











                    • Happy to help, just pay attention to the criteria in the for loop, in this case only ENBO is extracted. There are also very similar examples in the Python documentation here

                      – BernardL
                      Nov 16 '18 at 21:49





















                    • Yes!!! this did it. Thank you!

                      – FranceMadrid
                      Nov 16 '18 at 21:46











                    • Happy to help, just pay attention to the criteria in the for loop, in this case only ENBO is extracted. There are also very similar examples in the Python documentation here

                      – BernardL
                      Nov 16 '18 at 21:49



















                    Yes!!! this did it. Thank you!

                    – FranceMadrid
                    Nov 16 '18 at 21:46





                    Yes!!! this did it. Thank you!

                    – FranceMadrid
                    Nov 16 '18 at 21:46













                    Happy to help, just pay attention to the criteria in the for loop, in this case only ENBO is extracted. There are also very similar examples in the Python documentation here

                    – BernardL
                    Nov 16 '18 at 21:49







                    Happy to help, just pay attention to the criteria in the for loop, in this case only ENBO is extracted. There are also very similar examples in the Python documentation here

                    – BernardL
                    Nov 16 '18 at 21:49















                    0














                    Something like this should work.



                    print_next_line = False
                    for line1 in f:
                    if print_next_line:
                    print(line1)
                    print_next_line = False
                    if "ENBO" in line1:
                    print_next_line = True





                    share|improve this answer
























                    • This just prints out nothing for me :/. I also added print (line1) to end of last if statement

                      – FranceMadrid
                      Nov 16 '18 at 21:38


















                    0














                    Something like this should work.



                    print_next_line = False
                    for line1 in f:
                    if print_next_line:
                    print(line1)
                    print_next_line = False
                    if "ENBO" in line1:
                    print_next_line = True





                    share|improve this answer
























                    • This just prints out nothing for me :/. I also added print (line1) to end of last if statement

                      – FranceMadrid
                      Nov 16 '18 at 21:38
















                    0












                    0








                    0







                    Something like this should work.



                    print_next_line = False
                    for line1 in f:
                    if print_next_line:
                    print(line1)
                    print_next_line = False
                    if "ENBO" in line1:
                    print_next_line = True





                    share|improve this answer













                    Something like this should work.



                    print_next_line = False
                    for line1 in f:
                    if print_next_line:
                    print(line1)
                    print_next_line = False
                    if "ENBO" in line1:
                    print_next_line = True






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 16 '18 at 21:34









                    yperyper

                    2,60242636




                    2,60242636













                    • This just prints out nothing for me :/. I also added print (line1) to end of last if statement

                      – FranceMadrid
                      Nov 16 '18 at 21:38





















                    • This just prints out nothing for me :/. I also added print (line1) to end of last if statement

                      – FranceMadrid
                      Nov 16 '18 at 21:38



















                    This just prints out nothing for me :/. I also added print (line1) to end of last if statement

                    – FranceMadrid
                    Nov 16 '18 at 21:38







                    This just prints out nothing for me :/. I also added print (line1) to end of last if statement

                    – FranceMadrid
                    Nov 16 '18 at 21:38













                    0














                    The answer yper gave should work, but may I also suggest looking into JSON file formatting? This would allow you to assign a value to the key "ENBO" and then access that through a key:value pairing?



                    Not sure what you're reading the file for, or what generates it so can't guarantee that this approach would help you.






                    share|improve this answer




























                      0














                      The answer yper gave should work, but may I also suggest looking into JSON file formatting? This would allow you to assign a value to the key "ENBO" and then access that through a key:value pairing?



                      Not sure what you're reading the file for, or what generates it so can't guarantee that this approach would help you.






                      share|improve this answer


























                        0












                        0








                        0







                        The answer yper gave should work, but may I also suggest looking into JSON file formatting? This would allow you to assign a value to the key "ENBO" and then access that through a key:value pairing?



                        Not sure what you're reading the file for, or what generates it so can't guarantee that this approach would help you.






                        share|improve this answer













                        The answer yper gave should work, but may I also suggest looking into JSON file formatting? This would allow you to assign a value to the key "ENBO" and then access that through a key:value pairing?



                        Not sure what you're reading the file for, or what generates it so can't guarantee that this approach would help you.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 16 '18 at 21:38









                        MoralousMoralous

                        81112




                        81112























                            0














                            Do you mean that you wish to put the contents of a text file into a variable?
                            There are two ways you would do this, the first of which is just to put it all into one string (with only one line I think this is what you want):



                            f = open(txt.txt, "r") # opening the file

                            output = f.read().replace('n', '') # replacing the newline with spaces


                            You can just remove a bit of the second line to put it into an array of the lines.



                            output = f.read()





                            share|improve this answer




























                              0














                              Do you mean that you wish to put the contents of a text file into a variable?
                              There are two ways you would do this, the first of which is just to put it all into one string (with only one line I think this is what you want):



                              f = open(txt.txt, "r") # opening the file

                              output = f.read().replace('n', '') # replacing the newline with spaces


                              You can just remove a bit of the second line to put it into an array of the lines.



                              output = f.read()





                              share|improve this answer


























                                0












                                0








                                0







                                Do you mean that you wish to put the contents of a text file into a variable?
                                There are two ways you would do this, the first of which is just to put it all into one string (with only one line I think this is what you want):



                                f = open(txt.txt, "r") # opening the file

                                output = f.read().replace('n', '') # replacing the newline with spaces


                                You can just remove a bit of the second line to put it into an array of the lines.



                                output = f.read()





                                share|improve this answer













                                Do you mean that you wish to put the contents of a text file into a variable?
                                There are two ways you would do this, the first of which is just to put it all into one string (with only one line I think this is what you want):



                                f = open(txt.txt, "r") # opening the file

                                output = f.read().replace('n', '') # replacing the newline with spaces


                                You can just remove a bit of the second line to put it into an array of the lines.



                                output = f.read()






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Nov 16 '18 at 21:40









                                SollyBunnySollyBunny

                                111127




                                111127























                                    0














                                    The usual way I approach something like this is to read until I find the line that signals the start of the data I'm looking for, then gather the desired data. For this question, something like the following should work:



                                    f = open('txt.txt', "r")
                                    for line1 in f:
                                    if ("ENBO" in line1):
                                    break # Stops the loop
                                    if f: # Make sure you didn't hit the end of the file
                                    data_line = f.readline() # Grab the next line
                                    print(data_line)





                                    share|improve this answer




























                                      0














                                      The usual way I approach something like this is to read until I find the line that signals the start of the data I'm looking for, then gather the desired data. For this question, something like the following should work:



                                      f = open('txt.txt', "r")
                                      for line1 in f:
                                      if ("ENBO" in line1):
                                      break # Stops the loop
                                      if f: # Make sure you didn't hit the end of the file
                                      data_line = f.readline() # Grab the next line
                                      print(data_line)





                                      share|improve this answer


























                                        0












                                        0








                                        0







                                        The usual way I approach something like this is to read until I find the line that signals the start of the data I'm looking for, then gather the desired data. For this question, something like the following should work:



                                        f = open('txt.txt', "r")
                                        for line1 in f:
                                        if ("ENBO" in line1):
                                        break # Stops the loop
                                        if f: # Make sure you didn't hit the end of the file
                                        data_line = f.readline() # Grab the next line
                                        print(data_line)





                                        share|improve this answer













                                        The usual way I approach something like this is to read until I find the line that signals the start of the data I'm looking for, then gather the desired data. For this question, something like the following should work:



                                        f = open('txt.txt', "r")
                                        for line1 in f:
                                        if ("ENBO" in line1):
                                        break # Stops the loop
                                        if f: # Make sure you didn't hit the end of the file
                                        data_line = f.readline() # Grab the next line
                                        print(data_line)






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Nov 16 '18 at 21:51









                                        GreenMattGreenMatt

                                        13.7k64270




                                        13.7k64270























                                            0














                                            I would recommend just doing this:



                                            from pathlib import Path

                                            print(Path(MY_FILE).read_text().splitlines()[1])


                                            Using pathlib for your file operations is highly recommended. If you can't/won't use it, this is equivalent:



                                            with open(MY_FILE) as f:
                                            print(f.readlines()[1])





                                            share|improve this answer




























                                              0














                                              I would recommend just doing this:



                                              from pathlib import Path

                                              print(Path(MY_FILE).read_text().splitlines()[1])


                                              Using pathlib for your file operations is highly recommended. If you can't/won't use it, this is equivalent:



                                              with open(MY_FILE) as f:
                                              print(f.readlines()[1])





                                              share|improve this answer


























                                                0












                                                0








                                                0







                                                I would recommend just doing this:



                                                from pathlib import Path

                                                print(Path(MY_FILE).read_text().splitlines()[1])


                                                Using pathlib for your file operations is highly recommended. If you can't/won't use it, this is equivalent:



                                                with open(MY_FILE) as f:
                                                print(f.readlines()[1])





                                                share|improve this answer













                                                I would recommend just doing this:



                                                from pathlib import Path

                                                print(Path(MY_FILE).read_text().splitlines()[1])


                                                Using pathlib for your file operations is highly recommended. If you can't/won't use it, this is equivalent:



                                                with open(MY_FILE) as f:
                                                print(f.readlines()[1])






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Nov 16 '18 at 21:52









                                                roeen30roeen30

                                                56629




                                                56629























                                                    0














                                                    First of all, it is important to note that your file contains 3 lines, even if semantically those 3 lines represent only one entity.



                                                    Now, if your file is really this simple, and you really just want the second line, you can use the method readlines().
                                                    This will read the whole file and return a list, where each line of the file is represented by one item.



                                                    Then, if you know that your line is always on the second line (index 1), you can just access it directly.



                                                    here is the suggested solution:



                                                    f = open(txt.txt, "r")
                                                    all_lines = f.readlines()
                                                    requested_line = all_lines[1]


                                                    Also, I would like to suggest that you use the with syntax to open the file, so the resource is disposed of when it is no longer used:



                                                    with open(txt.txt, "r") as f:
                                                    all_lines = f.readlines()
                                                    requested_line = all_lines[1]


                                                    You can understand more about the with statement in the docs or in the developer's guide



                                                    Note that readlines() goes through the whole file, so if your file might be of an unknown length, you should probably refrain from using it.






                                                    share|improve this answer






























                                                      0














                                                      First of all, it is important to note that your file contains 3 lines, even if semantically those 3 lines represent only one entity.



                                                      Now, if your file is really this simple, and you really just want the second line, you can use the method readlines().
                                                      This will read the whole file and return a list, where each line of the file is represented by one item.



                                                      Then, if you know that your line is always on the second line (index 1), you can just access it directly.



                                                      here is the suggested solution:



                                                      f = open(txt.txt, "r")
                                                      all_lines = f.readlines()
                                                      requested_line = all_lines[1]


                                                      Also, I would like to suggest that you use the with syntax to open the file, so the resource is disposed of when it is no longer used:



                                                      with open(txt.txt, "r") as f:
                                                      all_lines = f.readlines()
                                                      requested_line = all_lines[1]


                                                      You can understand more about the with statement in the docs or in the developer's guide



                                                      Note that readlines() goes through the whole file, so if your file might be of an unknown length, you should probably refrain from using it.






                                                      share|improve this answer




























                                                        0












                                                        0








                                                        0







                                                        First of all, it is important to note that your file contains 3 lines, even if semantically those 3 lines represent only one entity.



                                                        Now, if your file is really this simple, and you really just want the second line, you can use the method readlines().
                                                        This will read the whole file and return a list, where each line of the file is represented by one item.



                                                        Then, if you know that your line is always on the second line (index 1), you can just access it directly.



                                                        here is the suggested solution:



                                                        f = open(txt.txt, "r")
                                                        all_lines = f.readlines()
                                                        requested_line = all_lines[1]


                                                        Also, I would like to suggest that you use the with syntax to open the file, so the resource is disposed of when it is no longer used:



                                                        with open(txt.txt, "r") as f:
                                                        all_lines = f.readlines()
                                                        requested_line = all_lines[1]


                                                        You can understand more about the with statement in the docs or in the developer's guide



                                                        Note that readlines() goes through the whole file, so if your file might be of an unknown length, you should probably refrain from using it.






                                                        share|improve this answer















                                                        First of all, it is important to note that your file contains 3 lines, even if semantically those 3 lines represent only one entity.



                                                        Now, if your file is really this simple, and you really just want the second line, you can use the method readlines().
                                                        This will read the whole file and return a list, where each line of the file is represented by one item.



                                                        Then, if you know that your line is always on the second line (index 1), you can just access it directly.



                                                        here is the suggested solution:



                                                        f = open(txt.txt, "r")
                                                        all_lines = f.readlines()
                                                        requested_line = all_lines[1]


                                                        Also, I would like to suggest that you use the with syntax to open the file, so the resource is disposed of when it is no longer used:



                                                        with open(txt.txt, "r") as f:
                                                        all_lines = f.readlines()
                                                        requested_line = all_lines[1]


                                                        You can understand more about the with statement in the docs or in the developer's guide



                                                        Note that readlines() goes through the whole file, so if your file might be of an unknown length, you should probably refrain from using it.







                                                        share|improve this answer














                                                        share|improve this answer



                                                        share|improve this answer








                                                        edited Nov 16 '18 at 21:53

























                                                        answered Nov 16 '18 at 21:48









                                                        OriOri

                                                        705816




                                                        705816






























                                                            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%2f53345693%2fhow-to-read-one-line-down-from-text-file-in-python%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

                                                            List item for chat from Array inside array React Native

                                                            Thiostrepton

                                                            Caerphilly