1

I am new to python and I am trying to iterate through a list and append every 8 lines from a file to a list. Which I will append to those elements and rewrite this list on a new file. What I am keep running into is getting specific sections out of the txt file that I want. Here is my code:

tester1=1
tester2=9
for n,line in enumerate(myList):
    if n>(tester1) and n<(tester2):
        tempList.append(line)
        tester1=tester1+8
        tester2=tester2+8

So I do not want line 0,1. But lines 2 through 8. Next I need it to go to line 9 through 17... and so on. This current code is giving me every 8th element in my txt file which was made into a list.

1 Answers1

0

In the simplest possible way, you could do:

with open('path/to/file.txt') as f:
    next(f); next(f)  # skip first two lines
    lst = []
    while True:
        try:
            lst.append([next(f) for _ in range(8)])
        except StopIteration:
            return lst
Adam Smith
  • 52,157
  • 12
  • 73
  • 112