Files and Exceptions
Files and Exceptions
y.
ud
st
ty
si
er
iv
un
FILES AND EXCEPTIONS
FILES
▪ To open a file, you specify its name and indicate whether you want to read or write
in
y.
>>> f = open("test.txt","w")
ud
>>> print f
st
<open file ’test.txt’, mode ’w’ at fe820>
ty
si
▪ First argument: Name of the file
er
▪ Second argument: mode (“r” for Read/”w” for Write)
iv
▪ If there is no file named test.txt, it will be created. If there already is one, it will be
un
replaced by the file we are writing.
▪ If we try to open a file that doesn’t exist, we get an error:
>>> f = open("test.cat","r")
IOError: [Errno 2] No such file or directory: ’test.cat’
WRITING DATA
in
▪ To put data in the file we invoke the write method on the file object with w
y.
ud
>>> f = open("test.txt","w")
>>> f.write("Now is the time")
st
>>> f.write("to close the file")
ty
si
er
▪ Closing the file tells the system that we are done writing and makes the file
iv
available for reading un
>>> f.close()
READING DATA
▪ To read the data from the file we invoke the read method on the file object with r
in
>>> f = open("test.txt",“r")
y.
>>> text = f.read()
ud
>>> print text
st
Now is the timeto close the file
ty
si
er
▪ Read can also take an argument that indicates how many characters to read
iv
un
>>> f = open("test.txt","r")
>>> print f.read(5)
Now i
READING CONTINUED
▪ If not enough characters are left in the file, read returns the remaining characters.
in
When we get to the end of the file, read returns the empty string:
y.
ud
>>> print f.read(1000006)
s the timeto close the file
st
>>> print f.read()
ty
si
>>>
er
iv
un
EXAMPLE 1
▪ The following function copies a file, reading and writing up to fifty characters at a time.
in
The first argument is the name of the original file; the second is the name of the new file
y.
ud
st
ty
si
er
iv
un
TEXT FILES
▪ A text file with three lines of text separated by newlines
in
y.
>>> f = open("test.dat","w")
>>> f.write("line one\nline two\nline three\n")
ud
>>> f.close()
st
▪ The readline method reads all the characters up to and including the next newline character:
ty
si
>>> f = open("test.dat","r")
>>> print f.readline()
er
line one
iv
>>>
un
▪ readlines returns all of the remaining lines as a list of strings:
>>> print f.readlines()
[’line two\012’, ’line three\012’]
EXAMPLE 2
in
▪ The following is an example of a line-processing program. filterFile makes a copy of
y.
oldFile, omitting any lines that begin with #:
ud
st
ty
si
er
iv
un
WRITING VARIABLES
▪ To write data types other than string, do
in
y.
>>> x = 52
ud
>>> f.write (str(x))
st
or use the Format Operator
ty
>>> cars = 52
si
>>> "%d" % cars
er
’52’
iv
Another example:
un
>>> cars = 52
>>> "In July we sold %d cars.“ % cars
’In July we sold 52 cars.’
WRITING VARIABLES – FORMAT OPERATOR
▪ %f for floats, %s for strings
in
y.
>>>
ud
▪"In %d days we made %f million %s." % (34,6.1,’dollars’)
’In 34 days we made 6.100000 million dollars.’
st
>>> "%d %d %d" % (1,2)
ty
TypeError: not enough arguments for format string
si
>>> "%d" % ’dollars’
er
TypeError: illegal argument type for built-in operation
iv
▪ For more control over the format of numbers, we can specify the number of digits as part of the format
un
sequence:
>>> "%6d" % 62
’ 62’
>>> "%12f" % 6.1
’ 6.100000’
The number after the percent sign is the minimum number of spaces the number will take up.
WRITING VARIABLES – FORMAT OPERATOR
▪ If the value provided takes fewer digits, leading spaces are added. If the number of spaces is
in
negative, trailing spaces are added:
y.
>>> "%-6d" % 62
ud
’62 ’
st
▪ For floating-point numbers, we can also specify the number of digits after the decimal point:
ty
si
>>> "%12.2f" % 6.1
’ 6.10’
er
iv
un
DIRECTORIES
▪ If you want to open a file somewhere else, you have to specify the path to the file, which is the name of
in
the directory (or folder) where the file is located:
y.
ud
>>> f = open("/usr/share/dict/words","r")
>>> print f.readline()
st
Aarhus
ty
si
▪ This example opens a file named words that resides in a directory named dict, which resides in share,
er
which resides in usr, which resides in the top-level directory of the system, called /.
iv
You cannot use / as part of a filename; it is reserved as a delimiter between directory and filenames.
un
PICKLING
▪ Things are written as strings in files. To get the original data structures (like lists,
in
dictionaries) back, use the concept of Pickling. To use it, import pickle and then open the file
y.
in the usual way:
ud
st
>>> import pickle
ty
>>> f = open("test.pck","w")
si
er
▪ To store a data structure, use the dump method and then close the file in the usual way:
iv
un
>>> pickle.dump(12.3, f)
>>> pickle.dump([1,2,3], f)
>>> f.close()
PICKLING - CONTINUED
in
▪ Then we can open the file for reading and load the data structures we dumped:
y.
ud
>>> f = open("test.pck","r")
st
>>> x = pickle.load(f)
ty
>>> x 12.3
si
>>> type(x)
er
<type ’float’>
iv
>>> y = pickle.load(f) un
>>> y [1, 2, 3]
>>> type(y)
<type ’list’>
EXCEPTIONS
▪ Whenever a runtime error occurs, it creates an exception. Usually, the program stops and Python prints
in
an error message.
y.
For example,
ud
>>> print 55/0
st
ZeroDivisionError: integer division or modulo
ty
si
>>> a = []
er
>>> print a[5]
IndexError: list index out of range
iv
>>> b = {}
un
>>> print b[’what’]
KeyError: what
in
about the error after the colon. Sometimes we want to execute an operation that
y.
could cause an exception, but we don’t want the program to stop. We can handle the
ud
exception using the try and except statements.
st
ty
si
er
iv
un
▪ The try statement executes the statements in the first block. If no exceptions occur, it
ignores the except statement. If an exception of type IOError occurs, it executes the
statements in the except branch and then continues.
EXCEPTIONS
in
▪ You can use multiple except blocks to handle different kinds of exceptions.
y.
ud
▪ If your program detects an error condition, you can make it raise an exception. Here
is an example that gets input from the user and checks for the value 17.
st
ty
si
er
iv
un
EXCEPTIONS
in
▪ The raise statement takes two arguments: the exception type and specific
y.
information about the error. ValueError is one of the exception types Python provides
ud
for a variety of occasions. Other examples include TypeError, KeyError, and my
st
favorite, NotImplementedError.
ty
▪ If the function that called inputNumber handles the error, then the program can
si
er
continue; otherwise, Python prints the error message and exits:
iv
un