07-Csci333 Lecture FileIOExceptions
07-Csci333 Lecture FileIOExceptions
07-Csci333 Lecture FileIOExceptions
Cameron Johnson
with thanks to Dr. Yuehua Wang
FILE INPUT/OUTPUT
& EXCEPTIONS
Goals
To read and write text files
To use loops to process collections of data
To write programs that manipulate files
To learn more about strings
To raise and handle exceptions
Problem Input file
32.0
54.0
Suppose you are given a text 67.5
80.25
file that contains a sequence 115.0
of floating-point values,
stored one value per line
You need to read the values and
Output file
write them to a new output file,
32.00
aligned in a column and 54.00
followed by their total and 67.50
80.25
average value 115.00
If the input file has the contents --------
Total: 348.75
The output file will contain Average: 69.75
File Input and Output
Introduction
infile == open("input.txt",
infile open("input.txt", "r")
"r")
outfile == open("output.txt",
outfile open("output.txt", "w")
"w")
Accessing a File
To access a file, you must first open it
Suppose you want to read data from a file named
input.txt, located in the same directory as the program
To open a file for reading, you must provide the name
of the file as the first argument to the open function
and the string "r" as the second argument:
infile == open("input.txt",
infile open("input.txt", "r")
"r")
infile.close()
outfile.close()
If your program exits without closing a file that
was opened for writing, some of the output may
not be written to the disk file
Syntax: Opening and Closing
Files
Example of Writing data
while line != “”
Examples of reading and writng numeric data
# Prompt the user for the name of the input and output files.
inputFileName = input("Input file name: ")
outputFileName = input("Output file name: ")
# Open the input and output files.
infile = open(inputFileName, "r")
outfile = open(outputFileName, "w")
# Read the input and write the output.
total = 0.0
count = 0
line = infile.readline()
sales =1000
outfile.write(str(sales) + '\n')
Number are read from a text file as strings
Must be converted to numeric type in order to
perform mathematical operations
Use int and float functions to convert string to
numeric value
Common Error
Backslashes in File Names
When using a String literal for a file name with
path information, you need to supply each
backslash twice:
infile == open("c:\\homework\\input.txt",
infile open("c:\\homework\\input.txt", "r")
"r")
A single backslash inside a quoted string is the
escape character, which means the next character
is interpreted differently (for example, ‘\n’ for a
newline character)
Useful
for when need
character to iterate over the whole string, such
in string:
as to count the occurrences of a specific character
Use indexing
Each character has an index specifying its position in
the string, starting at 0
General Format:
character = my_string[i]
Accessing the Individual Characters in a String (cont’d.)
Another Example
A schematic diagram
of the indices of the
string ‘foobar’ would
look like this:
The individual
characters can be
accessed by index as
shown to the right
String Review
len(string) function
can be used to obtain the length of a string
Useful to prevent loops from iterating beyond the end of a string
length
IndexError exception will occur
= len("World!") if:
# length is 6
You try to use an index that is out of range for the string
Likely to happen when loop iterates beyond the end of the string
String indices
can also be specified with Some examples of negative indexing:
string[index] = new_character
strip method
is essentially equivalent to invoking s.lstrip() and
s.rstrip() in succession. Without specifying argument, it
removes leading and trailing whitespace:
More examples
Challenge
For example
try: try:
Statements Statements
except exceptionType: except exceptionType:
Statements Statements
Try suite: statements that can potentially raise an
except exceptionType as
exception varName:
Statments
Handler: statements contained in except block
Try-Except: An Example
try ::
try
filename == input("Enter
filename input("Enter filename:
filename: ")
")
open() can raise an
infile == open(filename,
infile open(filename, "r")
"r")
IOError exception
line = infile.readline()
line = infile.readline()
value == int(line)
value int(line) int() can raise a
.. .. .. ValueError exception
except IOError
except IOError :: Execution transfers here if
print("Error: file
print("Error: file not
not found.")
found.") file cannot be opened
except ValueError
except ValueError as
as exception
exception ::
Execution transfers here if
print("Error:", str(exception))
print("Error:", str(exception))
the string cannot be
converted to an int
If no exception is raised,
handlers are skipped
Handling Multiple Exceptions
Often code in try suite can throw more than one type of exception
Need to write except clause for each type of exception that needs to
be handled
An except clause that does not list a specific exception will handle
any exception that is raised in the try suite
Should always be last in a series of except clauses
The else Clause
try/except statement may include an optional else clause,
which appears after all the except clauses
Aligned with try and except clauses
Syntax similar to else clause in decision structure
try:
Statements
except
exceptionType:
else
Statements
suite: block of statements executed after statements in try suite,
else:
only if no exceptions were raised
Statments
If exception was raised, the else suite is skipped
The finally Clause
try/except statement may include an optional finally clause, which
appears after all the except clauses
Aligned with try and except clauses
General format:
try:
Statements
except
exceptionType:
Statements
else:
Statments
finally:
Statments
try/exception/else/finally
outfile = open("demofile.txt","w")
try:
outfile.write("Hello World")
except:
print("Something went wrong when writing to the file")
else:
print("Well done")
finally:
outfile.close()
Homework 7
Create a python script that will load homework7WordSearchKey.txt and use it to
create a word search puzzle, then save that as homework7WordSearchPuzzle.txt
The example of this part was done in class; you may use as much of that as you like as long
as you ensure it works on your computer.
Create a second python script that will load your
homework7WordSearchPuzzle.txt as well as homework7WordSearchList.txt, and
then search the puzzle you’ve created and recreate the block from
homework7WordSearchKey.txt
The horizontal words should be almost trivial
The vertical words will require some careful thought on how to manipulate the strings,
and/or how to load the data.
There is a single diagonal word that will likely be the most challenging
Your code should be able to find words that are in the word list without knowing in advance
which direction they are facing (though no words will be backwards)
This homework is due in two weeks, on 30 March 2021 at 6:30 am.
There will be a homework next week, however, so do not put this one off; the extra time is
due to the complexity of the problem.