Contents
- file_handle.py
- robust_error_handling.py
- yearborn2.py
- yearborn.py
- years_dictionary2.py
- years_dictionary.py
file_handle.py 1/6
[top][prev][next]
# Demonstrate file handling exception
# Examples of errors:
# - file not found
# - don't have permission on the file
# Sara Sprenkle
import sys
def main():
infileName = input("What file do you want to read? ")
# put the "correct"/"usual" behavior within the try
try:
inFile = open(infileName, "r")
# normally, we would do some sort of processing of the file here.
inFile.close()
except IOError as exc: # exc is the name of the raised exception
print("Error reading \"" + infileName + "\".")
# could be a variety of different problems, so print out
# the exception
print(exc)
print(type(exc)) # not helpful output for the user; just for demo purposes
sys.exit(1)
outfileName = input("What file do you want to write? ")
try:
outFile = open(outfileName, "w")
# normally, we would do some sort of processing of the file here.
outFile.close()
except IOError as exc:
print("Error writing \"" + outfileName + "\".")
print(exc)
print(type(exc)) # not helpful output for the user; just for demo purposes
# no need to exit here because there is nothing else to do.
main()
robust_error_handling.py 2/6
[top][prev][next]
# Demonstrate file handling exception
# Examples of errors:
# - file not found
# - don't have permission on the file
# Sara Sprenkle
import sys
def main():
print("Let's do some more robust error handling")
isFileRead = False
while not isFileRead:
infileName = input("What file do you want to read? ")
# put the "correct"/"usual" behavior within the try
try:
inFile = open(infileName, "r")
# normally, we would do some sort of processing of the file here.
inFile.close()
isFileRead = True
except IOError as exc: # exc is the name of the raised exception
print("Error reading \"" + infileName + "\".")
# could be a variety of different problems, so print out
# the exception
print(exc)
print()
print("File read! now, let's do something with it...")
main()
yearborn2.py 3/6
[top][prev][next]
# Demonstrate validating user input
# by CSCI111
import sys
def main():
print("This program determines your birth year")
print("given your age and the current year \n")
try:
age = int(input("Enter your age: "))
currentyear = int(input("Enter the current year: "))
except ValueError:
print("Error: Your input was not in the correct form.")
print("Enter integers for your age and the current year")
sys.exit(1)
if age < 0 or age > 115:
print("Come on: you have to be a reasonable age.")
elif currentyear < 0:
print("You need to have a positive year.")
else:
birthyear=currentyear - age
print("You were either born in", birthyear, "or", birthyear-1)
main()
yearborn.py 4/6
[top][prev][next]
# Demonstrate validating user input
# by CSCI111
import sys
def main():
print("This program determines your birth year")
print("given your age and the current year \n")
try:
age = int(input("Enter your age: "))
currentyear = int(input("Enter the current year: "))
except:
print("Error: Your input was not in the correct form.")
print("Enter integers for your age and the current year")
sys.exit(1)
if age < 0 or age > 115:
print("Come on: you have to be a reasonable age.")
elif currentyear < 0:
print("You need to have a positive year.")
else:
birthyear=currentyear - age
print("You were either born in", birthyear, "or", birthyear-1)
main()
years_dictionary2.py 5/6
[top][prev][next]
# Given a file of the form <firstname> <classyear>,
# report how many students are in each class year
# by CSCI 111
FILENAME="data/roster.dat"
# open the file for reading
yearsFile = open(FILENAME, "r")
# create our accumulator dictionary
gradYearToCount = {}
# go through each line
for line in yearsFile:
# split at the space into the name and the year
rosterList = line.split()
year = rosterList[1]
# is this grad year in the dictionary?
if year in gradYearToCount:
# if it is, accumulate, update the count for that grad year
gradYearToCount[year] += 1
# Alternative solution
#count = gradYearToCount[year]
#count += 1
#gradYearToCount[year] = count
# else, create a new key with a value of 1
else:
gradYearToCount[year] = 1
yearsFile.close()
#print(gradYearToCount)
# Better yet, display in a nice way:
for gradyear in sorted(gradYearToCount):
numStudents = gradYearToCount[gradyear]
print( numStudents, "student(s) are in the class of", gradyear)
years_dictionary.py 6/6
[top][prev][next]
# Given a file of the form <firstname> <class>
# creates a mapping between the first names and class
# by CSCI 111
FILENAME="data/roster.dat"
# open the file for reading
yearsFile = open(FILENAME, "r")
# create our accumulator dictionary
nameToYear = {}
# go through each line
for line in yearsFile:
# split at the space into the name and the year
rosterList = line.split()
# key is the name, value is the year
name = rosterList[0]
year = rosterList[1]
# add mapping into the dictionary
nameToYear[name] = year
yearsFile.close()
print(nameToYear)
#repeatedly (until the user enters nothing)
while True:
# prompt for the student name and display their class year
studentName = input("What is the student's name? ")
if studentName == "":
break
if studentName in nameToYear:
year = nameToYear[studentName]
print(studentName, "is expected to graduate in", year)
else:
print(studentName, "is not on the roster")
Generated by GNU Enscript 1.6.6.