Home > Articles

Python Functions and Files

  • Print
  • + Share This

Work through an exercise that demonstrates how Python functions and files can work together to make useful stuff.

Save 35% off the list price* of the related book or multi-format eBook (EPUB + MOBI + PDF) with discount code ARTICLE.
* See informit.com/terms

This chapter is from the book

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)
10
11    def print_a_line(line_count, f):
12        print(line_count, f.readline())
13
14    current_file = open(input_file)
15
16    print("First let's print the whole file:\n")
17
18    print_all(current_file)
19
20    print("Now let's rewind, kind of like a tape.")
21
22    rewind(current_file)
23
24    print("Let's print three lines:")
25
26    current_line = 1
27    print_a_line(current_line, current_file)
28
29    current_line = current_line + 1
30    print_a_line(current_line, current_file)
31
32    current_line = current_line + 1
33    print_a_line(current_line, current_file)

Pay close attention to how we pass in the current line number each time we run print_a_line.

What You Should See

Exercise 20 Session

$ python3.6 ex20.py test.txt
First let's print the whole file:

This is line 1
This is line 2
This is line 3

Now let's rewind, kind of like a tape.
Let's print three lines:
1 This is line 1

2 This is line 2

3 This is line 3
  • + Share This
  • 🔖 Save To Your Account