File I/O

An application may receive input from a user.

An application may output text to a window for a user to view.

It is not practical to have a significant amount of data input by a user.

Computers store information in files.

A program that will process data must be able to input data from a file and perhaps output data to a file.

File Objects

File I/O is another example of object-oriented programming.

Again, with object-oriented programming objects are created and operations are "done on" the objects.

To do file I/O we first get a file object.

When getting a file object the file is opened.

When opening a file the name of the file is specified.

Once the file is opened its contents can be input using the file object.

When done the file should be closed.

Opening a File

When opening a file the open may fail.

For example, a file open may fail if the file does not exist.

It is necessary to check that the file open succeeded.

Example, open a file for input:

# Modules and import are covered later
from sys import exit

# Open the file whose name is in the variable file_name
# Exit if unsuccessful
try:
   in_file = open(file_name)
except:
   print("Couldn't open file:", file_name)
   exit(1)

The try section above can have one or more statements.

If a statement in the try section fails the except statements are executed.

If all statements in the try section succeed the except section statements are skipped.

File Name and File Objects

The file object is used for input and output.

The file name specifies a file somewhere in the computer's file system.

By default when opening a file the same directory where the program is located is searched for the file name specified in the open call.

Opening a File For Reading, Writing, Appending

A file may be opened in one of three modes.

  1. Read - Input from a file, this is the default if the parameter is omitted
  2. Write - Output to a file, the file is cleared first
  3. Append - Add to the end of the file

Note that when opening a file for writing if the file has anything stored in it that content is deleted.

The deleted contents are not recoverable.

from sys import exit

# Mode can be 'r' for read. 'w' for write, 'a' for append
mode = 'r'

# Open the file whose name is in the variable file_name
# Exit if unsuccessful
try:
   in_file = open(file_name, mode)
except:
   print("Couldn't open file:", file_name)
   exit(1)

File Input/Output Methods

Once a file has been opened successfully it can be read from or written to, according to how it was opened.

For file objects opened for input the readline method may be use to read a line from the file.

For file objects opened for output the write method may be use to write a line to the file.

readline Method Notes

For the readline method:

  • A string is returned, the characters of the line
  • The returned string contains the newline at the end of the line. (The very last line in the file may not have a newline after it.)
  • If the line is empty there is still the newline that will be returned.
  • If the string is totally empty, then that indicates the end of the file was reached.

File Input Example

from sys import exit

# Prompt, input file name
file_name = input('Please enter a file name: ')

# Open the file whose name is in the variable file_name
# Exit if unsuccessful
try:
   in_file = open(file_name)
except:
   print("Couldn't open file:", file_name)
   exit(1)

# Open succeeded, read lines and print with line number
ctr = 1
while True: # Input a line
   line = in_file.readline()
   # If line is empty we are done, exit the loop
   if not line:
       break
   # Output
   print(ctr, line)
   ctr = ctr + 1

File Output Example

from sys import exit

# Prompt, input file name
file_name = input('Please enter a file name: ')

# Open the file whose name is in the variable file_name
# Return if unsuccessful
try:
   out_file = open(file_name, 'w')
except:
   print("Couldn't open file:", file_name)
   exit(1)

# Open succeeded, write numbers, squares, and cubes to file
ctr = 1
while ctr < 100:
   # Compute
   square = ctr * ctr
   cube   = square * ctr

    # Consruct string for output
   out_str = '%5d %6d %6d\n' % (ctr, square, cube)

   # Output a line
   out_file.write(out_str)
   ctr = ctr + 1