Example code - File Reading

From 22101
Jump to navigation Jump to search

Numbering and printing a chunk of file

print("Numbers and prints a section of a file.")
filename = input("Filename: ")
fromline = int(input("From line: "))
toline   = int(input("To line: "))

with open(filename, "r") as infile:
    # keep track of the line number
    linenumber = 0
    # iterate over the lines in the file
    for line in infile:
        linenumber += 1
        # went past the required last line
        if linenumber > toline:
            pass
        # reached the line we want to print from
        elif linenumber >= fromline:
            print(linenumber, "\t", line, sep='', end = '')