Python by Swaroop C H - HTML preview
Download the book in PDF, ePub, Kindle for a complete version.
Using Finally
Example 13.3. Using Finally
#!/usr/bin/python# Filename: finally.py import time
try: f = file('poem.txt')
while True: # our usual file-reading idiom
if len(line) == 0:
break
time.sleep(2)
print line,
finally:f.close()
print 'Cleaning up...closed the file'
Output
$ python finally.py
Programming is fun
When the work is done
Cleaning up...closed the file Traceback (most recent call last):
KeyboardInterrupt
How It Works
We do the usual file-reading stuff, but I've arbitrarily introduced a way of sleeping for 2 seconds before printing each line using thetime.sleep method. The only reason is so that the program runs slowly (Python is very fast by nature). When the program is still running, press Ctrl-c to interrupt/cancel the program.
Observe that aKeyboardInterrupt exception is thrown and the program exits, but before the program exits, the finally clause is executed and the file is closed.