Homework - Printing lines of a file between two line numbers
Using Python, how do I print the lines of a text fil开发者_运维问答e, 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()
精彩评论