0

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

user3324136
  • 415
  • 5
  • 20
  • Is your actual goal really to "index" the file, or just to iterate lines pairwise? – MisterMiyagi Nov 29 '21 at 17:34
  • 1
    Does this answer your question? [Iterate a list as pair (current, next) in Python](https://stackoverflow.com/questions/5434891/iterate-a-list-as-pair-current-next-in-python) – MisterMiyagi Nov 29 '21 at 17:35
  • Hi MisterMiyagi, Thank you for your answer. My goal is to look at the next line to see if it starts with a hyphens and if it does, then I will print the current line, so the next line (starting with a hypen) will begin with a hyphen. Does that make sense? – user3324136 Nov 29 '21 at 17:40
  • Are you asking how to index a list?? – juanpa.arrivillaga Nov 29 '21 at 17:56

2 Answers2

1

You can just access it from the list as you normally would, this will cause an exception on the last iteration so I added a check to prevent 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):
            if index < len(lines) - 1:
                next_line = lines[index+1]
                print(f'Index is {index + 1}')
                # Do something here
Erik McKelvey
  • 1,650
  • 1
  • 12
  • 23
1

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
Ratery
  • 2,863
  • 1
  • 5
  • 26