Example code - File Reading

From 22101
Revision as of 17:33, 1 March 2024 by WikiSysop (talk | contribs) (Created page with "== Numbering and printing a chunk of file == <pre> 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: pas...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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 = '')