Home > Software engineering >  How can I get the line of index 1 when enumerating lines in Python
How can I get the line of index 1 when enumerating lines in Python

Time:11-30

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

CodePudding user response:

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

CodePudding user response:

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
  • Related