Exercise 20. Functions and Files

Remember your checklist for functions, then do this exercise paying close attention to how functions and files can work together to make useful stuff.

ex20.py

 1    from sys import argv 2 3    script, input_file = argv 4 5    def print_all(f): 6        print(f.read()) 7 8    def rewind(f): 9        f.seek(0)1011    def print_a_line(line_count, f):12        print(line_count, f.readline())1314    current_file = open(input_file)1516    print("First let's print the whole file:\n")1718    print_all(current_file)1920    print("Now let's rewind, kind of like a tape.")2122    rewind(current_file)2324    print("Let's print three lines:")2526    current_line = 127    print_a_line(current_line ...

Get Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.