File IO
File IO
>>> f = open("hours.txt")
>>> f.read()
'123 Susan 12.5 8.1 7.6 3.2\n
456 Brad 4.0 11.6 6.5 2.7 12\n
789 Jenn 8.0 8.0 8.0 8.0 7.5\n'
File Input Template
• A template for reading files in Python:
name = open("filename")
for line in name:
statements
• expected output:
>>> input_stats("carroll.txt")
longest line = 42 characters
the jaws that bite, the claws that catch,
Exercise Solution
def input_stats(filename):
input = open(filename)
longest = ""
for line in input:
if len(line) > len(longest):
longest = line
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
The finally statement
• The finally: statement is executed under all circumstances even if an
exception is thrown.
• Cleanup statements such as closing files can be added to a finally
stetement.
Finally statement
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
finally:
f.close() # Called with or without exceptions.
Error Handling With Exceptions
• Exceptions are used to deal with extraordinary errors
(‘exceptional ones’).
• Typically these are fatal runtime errors (“crashes” program)
• Example: trying to open a non-existent file
• Basic structure of handling exceptions
try:
Attempt something where exception error may happen
except <exception type>:
React to the error
else: # Not always needed
What to do if no error is encountered
finally: # Not always needed
Actions that must always be performed
Exceptions: File Example
• Name of the online example: file_exception.py
• Input file name: Most of the previous input files can be used e.g. “input1.txt”
inputFileOK = False
while (inputFileOK == False):
try:
inputFileName = input("Enter name of input file: ")
inputFile = open(inputFileName, "r")
except IOError:
print("File", inputFileName, "could not be opened")
else:
print("Opening file", inputFileName, " for reading.")
inputFileOK = True
inputOK = False
while (inputOK == False):
try:
num = input("Enter a number: ")
num = float(num)
except ValueError: # Can’t convert to a number
print("Non-numeric type entered '%s'" %num)
else: # All characters are part of a number
inputOK = True
num = num * 2
print(num)
Example of using Files
>>> f=open("f.py","r")
>>> s=f.read()
>>> print(s)
def fac(n):
r=1
for i in range(1,n+1):
r=r*i
return r
import sys
n = int(sys.argv[1])
print("The factorial of ", n, " is ", fac(n))
>>> f.close()
>>>
Predefined cleanup actions
• The with statement will automatically close the file once it is no
longer in use.
with open("myfile.txt") as f:
for line in f:
print line