Search code examples
pythonpython-3.xenumerate

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

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