This lab provides exercises on file I/O.
Download lab8.zip, place it in your
directory, and unzip the file.
Develop this part in the
convert directory in files
float_default function takes a string and a default
float value. If the argument string represents a float value, then this
function will return that value (as a float). If such a conversion is not
possible, then the function will return the provided default value.
Conversion of a string to a float can be accomplished by passing the
string as an argument to
float. This operation can, however,
float('xyz')). An invalid conversion attempt
result in an exception being raised.
Exceptions are covered in detail in CSC 102, so we will use a simple
case here. In short, your code will
try something. If that
something works, then great ... continue on. If that something does not
work, then "catch" the exception and so something else. You can think of
this as asking for forgiveness instead of asking for permission. The
code outline below gives the simple structure of working with operations
that may raise exceptions.
try: # what you want to attempt to do except: # what to do if the previous code raises an exception
float_default function to convert a string to a
float, returning the provided default value if the conversion fails.
Develop the following in the
file directory in
Write a program that takes a single command-line argument. This argument
should be the name of a file to open for reading (if the argument is not
provided or the file cannot be opened, then print an error message and
terminate the program using
Your program should open the file and read each line until
is reached. Each line in the file will consist of two float values. For
each line, read the float values and print their sum. If a line is missing
a value or if one of the values cannot be converted, then print an error
message for that line.
Demonstrate each part of the lab to your instructor to have this lab recorded as completed. In addition, be prepared to show the source code to your instructor.
The handin command will vary by section.
Those in Aaron Keen's sections will not submit the lab.