Programming with Python
File I/O
Exceptions
Modules and Import
!1
Jun-17 Programming
File I/O
2
Jun-17 Programming
File I/O
• Files are persistent storage
2
Jun-17 Programming
File I/O
• Files are persistent storage
• Allow data to be stored beyond program
lifetime
2
Jun-17 Programming
File I/O
• Files are persistent storage
• Allow data to be stored beyond program
lifetime
• The basic operations on files are
– open, close, read, write
2
Jun-17 Programming
File I/O
• Files are persistent storage
• Allow data to be stored beyond program
lifetime
• The basic operations on files are
– open, close, read, write
• Python treat files as sequence of lines
– sequence operations work for the data read
from files
2
Jun-17 Programming
File I/O: open and close
3
Jun-17 Programming
File I/O: open and close
open(filename, mode)
3
Jun-17 Programming
File I/O: open and close
open(filename, mode)
• While opening a file, you need to supply
– The name of the file, including the path
– The mode in which you want to open a file
– Common modes are r (read), w (write), a (append)
3
Jun-17 Programming
File I/O: open and close
open(filename, mode)
• While opening a file, you need to supply
– The name of the file, including the path
– The mode in which you want to open a file
– Common modes are r (read), w (write), a (append)
• Mode is optional, defaults to r
3
Jun-17 Programming
File I/O: open and close
open(filename, mode)
• While opening a file, you need to supply
– The name of the file, including the path
– The mode in which you want to open a file
– Common modes are r (read), w (write), a (append)
• Mode is optional, defaults to r
• open(..) returns a file object
3
Jun-17 Programming
File I/O: open and close
open(filename, mode)
• While opening a file, you need to supply
– The name of the file, including the path
– The mode in which you want to open a file
– Common modes are r (read), w (write), a (append)
• Mode is optional, defaults to r
• open(..) returns a file object
• close() on the file object closes the file
– finishes any buffered operations
3
Jun-17 Programming
File I/O: Example
• Do some writing
• How to do it?
• see the next few slides
4
Jun-17 Programming
File I/O: read, write and append
5
Jun-17 Programming
File I/O: read, write and append
• Reading from an open file returns the
contents of the file
– as sequence of lines in the program
5
Jun-17 Programming
File I/O: read, write and append
• Reading from an open file returns the
contents of the file
– as sequence of lines in the program
• Writing to a file
– IMPORTANT: If opened with mode 'w', clears
the existing contents of the file
– Use append mode ('a') to preserve the
contents
– Writing happens at the end
5
Jun-17 Programming
File I/O: Examples
6
Jun-17 Programming
File I/O: Examples
6
Jun-17 Programming
File I/O: Examples
6
Jun-17 Programming
File I/O: Examples
( )
( )
7
Jun-17 Programming
File I/O: Examples
( )
( )
7
Jun-17 Programming
File I/O: Examples
( )
( )
7
Jun-17 Programming
File I/O: Examples
( )
( )
7
Jun-17 Programming
File I/O: Examples
( )
( )
7
Jun-17 Programming
File I/O: Examples
( )
8
Jun-17 Programming
File I/O: Examples
( )
8
Jun-17 Programming
File I/O: Examples
( )
8
Jun-17 Programming
File I/O: Examples
( )
Note empty line due to '\n'
8
Jun-17 Programming
File I/O: Examples
( )
Note empty line due to '\n'
8
Jun-17 Programming
File I/O: Examples
( )
]
9
Jun-17 Programming
File I/O: Examples
( )
]
9
Jun-17 Programming
File I/O: Examples
( )
]
9
Jun-17 Programming
File I/O: Examples
Note the use of for ... in
for sequence
( )
]
9
Jun-17 Programming
File I/O: Examples
Note the use of for ... in
for sequence
( )
]
9
Jun-17 Programming
File I/O: Examples
( )
( )
( )
10
Jun-17 Programming
File I/O: Examples
( )
( )
( )
10
Jun-17 Programming
File I/O: Examples
( )
( )
( )
10
Jun-17 Programming
File I/O: Examples
( )
( )
( )
10
Jun-17 Programming
File I/O: Examples
( )
( )
( )
10
Jun-17 Programming
Exceptions
11
Jun-17 Programming
Exceptions
11
Jun-17 Programming
Exceptions
12
Jun-17 Programming
Exceptions
• Exceptions are Pythons's way of telling user
that something unexpected has happened
12
Jun-17 Programming
Exceptions
• Exceptions are Pythons's way of telling user
that something unexpected has happened
• Most often an indication of some failure
– Access violation (writing to a read-only file)
– Missing resource (reading a non-existent file)
– Type incompatibility (multiplying two strings)
– Bound violation (accessing a string beyond
limit)
12
Jun-17 Programming
Exceptions
• Exceptions are Pythons's way of telling user
that something unexpected has happened
• Most often an indication of some failure
– Access violation (writing to a read-only file)
– Missing resource (reading a non-existent file)
– Type incompatibility (multiplying two strings)
– Bound violation (accessing a string beyond
limit)
• We have seen exceptions in our example
12
Jun-17 Programming
Exceptions
13
Jun-17 Programming
Exceptions
13
Jun-17 Programming
Exceptions
Exception when reading a closed fil
13
Jun-17 Programming
Exceptions can be Handled
14
Jun-17 Programming
Exceptions can be Handled
• To recover from unexpected operation
14
Jun-17 Programming
Exceptions can be Handled
• To recover from unexpected operation
• try ... except ... else ...
14
Jun-17 Programming
Exceptions can be Handled
• To recover from unexpected operation
• try ... except ... else ...
try:
Operations that can raise exceptions.
except [Optional list of exceptions] :
In case of exceptions, do the recovery.
else: # else is optional
If no exception then do normal things.
14
Jun-17 Programming
Exceptions can be Handled
• To recover from unexpected operation
• try ... except ... else ...
try:
Operations that can raise exceptions.
except [Optional list of exceptions] :
In case of exceptions, do the recovery.
else: # else is optional
If no exception then do normal things.
• try ... finally ...
14
Jun-17 Programming
Exceptions can be Handled
• To recover from unexpected operation
• try ... except ... else ...
try:
Operations that can raise exceptions.
except [Optional list of exceptions] :
In case of exceptions, do the recovery.
else: # else is optional
If no exception then do normal things.
• try ... finally ...
try:
Operations that can raise exceptions.
finally:
Execute irrespective of whether exception
was raised or not. Typically clean-up stuff.
14
Jun-17 Programming
Example
( )
( )
15
Jun-17 Programming
More about try…except
16
Jun-17 Programming
More about try…except
• A try statement may have more than one
except clause
▪ to specify handlers for different exceptions.
16
Jun-17 Programming
More about try…except
• A try statement may have more than one
except clause
▪ to specify handlers for different exceptions.
• At most one handler will be executed.
16
Jun-17 Programming
More about try…except
• A try statement may have more than one
except clause
▪ to specify handlers for different exceptions.
• At most one handler will be executed.
• An except clause may name multiple
exceptions as a parenthesized tuple.
16
Jun-17 Programming
More about try…except
• A try statement may have more than one
except clause
▪ to specify handlers for different exceptions.
• At most one handler will be executed.
• An except clause may name multiple
exceptions as a parenthesized tuple.
• The last except clause may omit the
exception name
– Catches any exception
16
Jun-17 Programming
Modules
17
Jun-17 Programming
Modules
• As program gets longer, need to organize them
for easier access and easier maintenance.
17
Jun-17 Programming
Modules
• As program gets longer, need to organize them
for easier access and easier maintenance.
• Reuse same functions across programs without
copying its definition into each program.
17
Jun-17 Programming
Modules
• As program gets longer, need to organize them
for easier access and easier maintenance.
• Reuse same functions across programs without
copying its definition into each program.
• Python allows putting definitions in a file
– use them in a script or in an interactive instance of
the interpreter
17
Jun-17 Programming
Modules
• As program gets longer, need to organize them
for easier access and easier maintenance.
• Reuse same functions across programs without
copying its definition into each program.
• Python allows putting definitions in a file
– use them in a script or in an interactive instance of
the interpreter
• Such a file is called a module
– definitions from a module can be imported into
other modules or into the main module
17
Jun-17 Programming
Modules
18
Jun-17 Programming
Modules
• A module is a file containing Python
definitions and statements.
18
Jun-17 Programming
Modules
• A module is a file containing Python
definitions and statements.
• The file name is the module name with
the suffix .py appended.
18
Jun-17 Programming
Modules
• A module is a file containing Python
definitions and statements.
• The file name is the module name with
the suffix .py appended.
• Within a module, the module’s name is
available in the global variable __name__.
18
Jun-17 Programming
Modules Example
fib.py - C:\
19
Jun-17 Programming
Modules Example
20
Jun-17 Programming
Modules Example
20
Jun-17 Programming
Modules Example
20
Jun-17 Programming
Modules Example
20
Jun-17 Programming
Modules Example
Within a module, the
module’s name is
available as the value of
the global variable
Jun-17 Programming
__name__. 20
Importing Specific Functions
21
Jun-17 Programming
Importing Specific Functions
• To import specific functions from a module
21
Jun-17 Programming
Importing Specific Functions
• To import specific functions from a module
21
Jun-17 Programming
Importing Specific Functions
• To import specific functions from a module
21
Jun-17 Programming
Importing Specific Functions
• To import specific functions from a module
21
Jun-17 Programming
Importing Specific Functions
• To import specific functions from a module
21
Jun-17 Programming
Importing Specific Functions
• To import specific functions from a module
• This brings only the imported functions in the current
symbol table
– No need of modulename. (absence of fib. in the example)
21
Jun-17 Programming
Importing ALL Functions
22
Jun-17 Programming
Importing ALL Functions
• To import all functions from a module, in the
current symbol table
22
Jun-17 Programming
Importing ALL Functions
• To import all functions from a module, in the
current symbol table
• This imports all names except those beginning
with an underscore (_).
22
Jun-17 Programming
__main__ in Modules
23
Jun-17 Programming
__main__ in Modules
• When you run a module on the command line with
python fib.py <arguments>
23
Jun-17 Programming
__main__ in Modules
• When you run a module on the command line with
python fib.py <arguments>
the code in the module will be executed, just as if
23
Jun-17 Programming
__main__ in Modules
• When you run a module on the command line with
python fib.py <arguments>
the code in the module will be executed, just as if
you imported it, but with the __name__ set to
23
Jun-17 Programming
__main__ in Modules
• When you run a module on the command line with
python fib.py <arguments>
the code in the module will be executed, just as if
you imported it, but with the __name__ set to
"__main__".
23
Jun-17 Programming
__main__ in Modules
• When you run a module on the command line with
python fib.py <arguments>
the code in the module will be executed, just as if
you imported it, but with the __name__ set to
"__main__".
• By adding this code at the end of your module
if __name__ == "__main__":
... # Some code here
23
Jun-17 Programming
__main__ in Modules
• When you run a module on the command line with
python fib.py <arguments>
the code in the module will be executed, just as if
you imported it, but with the __name__ set to
"__main__".
• By adding this code at the end of your module
if __name__ == "__main__":
... # Some code here
you can make the file usable as a script as well as an
23
Jun-17 Programming
__main__ in Modules
• When you run a module on the command line with
python fib.py <arguments>
the code in the module will be executed, just as if
you imported it, but with the __name__ set to
"__main__".
• By adding this code at the end of your module
if __name__ == "__main__":
... # Some code here
you can make the file usable as a script as well as an
importable module
23
Jun-17 Programming
__main__ in Modules
24
Jun-17 Programming
__main__ in Modules
if __name__ == "__main__":
import sys
print (fib_iter(int(sys.argv[1])))
24
Jun-17 Programming
__main__ in Modules
if __name__ == "__main__":
import sys
print (fib_iter(int(sys.argv[1])))
• This code parses the command line only if the
module is executed as the “main” file:
$ python fib.py 10
55
24
Jun-17 Programming
__main__ in Modules
if __name__ == "__main__":
import sys
print (fib_iter(int(sys.argv[1])))
• This code parses the command line only if the
module is executed as the “main” file:
$ python fib.py 10
55
• If the module is imported, the code is not run:
24
Jun-17 Programming
__main__ in Modules
if __name__ == "__main__":
import sys
print (fib_iter(int(sys.argv[1])))
• This code parses the command line only if the
module is executed as the “main” file:
$ python fib.py 10
55
• If the module is imported, the code is not run:
>>> import fib
24
Jun-17 Programming