Function and file in Python

Function and file in Python

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

1 from sys import argv
3 script, input_file = argv
5 def print_all(f):
6 print
8 def rewind(f):
11 def print_a_line(line_count, f):
12 print line_count, f.readline()
14 current_file = open(input_file)
16 print "First let's print the whole file:\n"
18 print_all(current_file)
20 print "Now let's rewind, kind of like a tape."
22 rewind(current_file)
24 print "Let's print three lines:"
26 current_line = 1
27 print_a_line(current_line, current_file)
29 current_line = current_line + 1
30 print_a_line(current_line, current_file)
32 current_line = current_line + 1
33 print_a_line(current_line, current_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

Study Drills

  1. Go through and write English comments for each line to understand what’s going on.
  2. Each time print_a_line is run, you are passing in a variable current_line. Write out what current_line is equal to on each function call, and trace how it becomes line_count in print_a_line.
  3. Research online what the seek function for file does. Try pydocfile and see if you can figure it out from there.
  4. Research the shorthand notation += and rewrite the script to use that.

What is f in the print_all and other functions?

A file in Python is kind of like an old tape drive on a mainframe, or maybe a DVD player. Each time you do, you’re moving to the start of the file.

Why are there empty lines between the lines in the file?

The readline() function returns the \n that’s in the file at the end of that line.

Why does seek(0) not set the current_line to 0?

First, the seek() function is dealing in bytes, not lines. Second, current_line is just a variable and has no real connection to the file at all. We are manually incrementing it.