Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I get the line of index + 1 when enumerating lines in Python

I am reading through the lines of a file using the code for index, line in enumerate(lines):. I can access the string of the current line using (line).

Is it possible to access the next line to look ahead? I have tried to access this by using next_line = line(index + 1) but this is creating an error.

Code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

with open(sys.argv[1]) as f1:
    with open(sys.argv[2], 'a') as f2:
        lines = f1.readlines()
        prev_line = ""
        string_length = 60
        for index, line in enumerate(lines):
            next_line = line(index + 1)
            print(f'Index is {index + 1}')
            # Do something here

>Solution :

line is a string therefore you can not do what you need.
Try something like this:

with open(sys.argv[1]) as f1:
    with open(sys.argv[2], 'a') as f2:
        lines = f1.readlines()
        prev_line = ""
        string_length = 60
        for index, line in enumerate(lines):
            try:
                next_line = lines[index + 1]
            except IndexError:
                pass
            print(f'Index is {index + 1}')
            # Do something here
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading