0

I currently have a function that takes each line of filename and adds each line to a list as its own element. However, I'd like to only be able to take the first num lines of the file. For example, if num = 2, the function only adds the first two lines of the file into the list. Here's what I have so far:

def storeFile(filename, num):
    listOfLines = []
    for line in open(filename, 'r').readlines():
        listOfLines.append(line.strip())
    return listOfLines

Any help would be appreciated!

  • there's many ways to do this. `if`, `range`, `enumerate`, but you might want to look at `pandas` with `read_csv()` as well. – MattR Nov 12 '19 at 18:02
  • 1
    Possible duplicate of [Read first N lines of a file in python](https://stackoverflow.com/questions/1767513/read-first-n-lines-of-a-file-in-python) – MattR Nov 12 '19 at 18:02

0 Answers0