exceptions_finally.py 563 B

12345678910111213141516171819202122232425
  1. import sys
  2. import time
  3. f = None
  4. try:
  5. f = open("poem.txt")
  6. # Our usual file-reading idiom
  7. while True:
  8. line = f.readline()
  9. if len(line) == 0:
  10. break
  11. print(line, end='')
  12. sys.stdout.flush()
  13. print("Press ctrl+c now")
  14. # To make sure it runs for a while
  15. time.sleep(2)
  16. except IOError:
  17. print("Could not find file poem.txt")
  18. except KeyboardInterrupt:
  19. print("!! You cancelled the reading from the file.")
  20. finally:
  21. if f:
  22. f.close()
  23. print("(Cleaning up: Closed the file)")