|
@@ -178,19 +178,23 @@ Save as `finally.py`:
|
|
|
~~~python
|
|
|
import time
|
|
|
|
|
|
+f = None
|
|
|
try:
|
|
|
- f = open('poem.txt')
|
|
|
- while True: # our usual file-reading idiom
|
|
|
+ f = open("poem.txt")
|
|
|
+ while True: # our usual file-reading idiom
|
|
|
line = f.readline()
|
|
|
if len(line) == 0:
|
|
|
break
|
|
|
- print(line, end='')
|
|
|
- time.sleep(2) # To make sure it runs for a while
|
|
|
+ print(line, end="", flush=True)
|
|
|
+ time.sleep(2) # To make sure it runs for a while
|
|
|
+except FileNotFoundError:
|
|
|
+ print("Could not find file poem.txt")
|
|
|
except KeyboardInterrupt:
|
|
|
- print('!! You cancelled the reading from the file.')
|
|
|
+ print("!! You cancelled the reading from the file.")
|
|
|
finally:
|
|
|
- f.close()
|
|
|
- print('(Cleaning up: Closed the file)')
|
|
|
+ if f:
|
|
|
+ f.close()
|
|
|
+ print("(Cleaning up: Closed the file)")
|
|
|
~~~
|
|
|
|
|
|
Output:
|
|
@@ -216,6 +220,9 @@ Observe that the `KeyboardInterrupt` exception is thrown and the
|
|
|
program quits. However, before the program exits, the finally clause
|
|
|
is executed and the file object is always closed.
|
|
|
|
|
|
+Note that we use `flush=True` in the call to `print()` so that it
|
|
|
+prints to the screen immediately.
|
|
|
+
|
|
|
## The with statement ##
|
|
|
|
|
|
Acquiring a resource in the `try` block and subsequently releasing the
|