1

I have a text file that is 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 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 skip the first two row so I can store everything else into my list?

2
  • 1
    I would probably use numpy.genfromtxt (docs) with skip_header=2 Commented Dec 5, 2015 at 11:44
  • 1
    probably the shortest solution with your existing code will be myList = myList[2:] Commented Dec 5, 2015 at 11:48

3 Answers 3

5

You can use next()

def readData():
    with open("football.txt", "r") as MyFile:
        for i in range(2):
            next(myFile) # skip line
        myList = [lines.split() for lines in myFile]
    return myList
Sign up to request clarification or add additional context in comments.

1 Comment

Another note that we also can use f.readline() or f.seek() to skip lines. Maybe clearer than next()...however this is also a works solution, so just a note.
1

You can also use the readlines() for this purpose

myFile = open("football.txt", "r")
lines = myFile.readlines()[2:] #To skip two lines.
#rest of the code

You could also specify the number of lines you want to skip.

Comments

1

To skip lines in Python 3...

print('\n')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.