简体   繁体   中英

Homework - Printing lines of a file between two line numbers

Using Python, how do I print the lines of a text file, given a starting and ending line number?

I have come up with a function, but this doesn't work.

def printPart(src, des, varFile):
    returnLines = ""
    for curLine in range(src, des):
        returnLines += linecache.getline(varFile, curLine)
    return returnLines

Since file objects are iterable in Python, you can apply all the functions from itertools to them. Have a look at itertools.islice() . (Since this is homework, I'll leave the details to you.)

I would start with the first line in the file, using readline() reading each line counting count += 1 . once count gets to the start line number, start printing. Once it gets to the last line number, sys.exit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM