How can I skip the first two rows when reading a text file in Python and store everything else into my list?
I have a text file laid out like this:
Text Text
Text Text Text Text Text
Text Num Num Num Num
Text Num Num Num Num
Text Num Num Num Num
My current code is:
def readData():
myList =
myFile = open(“football.txt”, “r”)
for lines in myFile:
league = lines.split()
myList.append(league)
return myList
How can I modify the code to skip the first two rows and store the remaining lines into my list?
Ah, skipping lines in Python, something I’ve done quite a few times. One simple way to do it is by using readlines()
. You can read all lines from the file and just slice the list from the third line onward. Like this:
myFile = open("football.txt", "r")
lines = myFile.readlines()[2:] # Skips the first two lines
# rest of the code
This is straightforward when you know exactly how many lines you need to skip. But, let’s say you’re looking for a more flexible approach…
Yeah, that works fine! But if you’re after something more flexible, I’d recommend using islice()
from the itertools
module. It gives you more control over how many lines you want to skip. Here’s how:
from itertools import islice
myFile = open("football.txt", "r")
lines = list(islice(myFile, 2, None)) # Skip the first two lines
# rest of the code
It’s nice because it allows you to skip any number of lines, or even continue reading the rest of the file. It’s kind of a neat trick when you need a bit more control over how to skip a line in Python!
Great points, @dimplesaini.230! Another approach is using a simple for
loop with a counter. It’s super handy when you need to do more than just skip lines, like processing or transforming the data. Here’s how I’d do it:
myFile = open("football.txt", "r")
myList = []
for i, line in enumerate(myFile):
if i < 2: # Skip the first two lines
continue
myList.append(line.split())
# rest of the code
This way, you’re keeping track of the line numbers, which can be useful if you need to skip different numbers of lines or even apply some logic based on the line content. It’s a simple and effective way of understanding how to skip a line in Python while also manipulating the data you want.