Welcome 🤗! In the next ~4h we will cover:

A safety net - a metaphor for exception handling. Marek Slusarczyk, CC BY 3.0, via Wikimedia Commons
Test¶
(20 min)
Learning goals¶
read, write to a file and modify a file
Write code that handles exceptions
Preparation review¶
Question pool¶
We used
input()andprint()to input and and output before. What is the motivation for using files in a program?You are working in a fashion company and would like to replace the telephone- and paper-based ordering pipeline with a digital one and start writing a simple prototype. Which Python file-related functions could be useful?
What are the three main modes used to open a file? What are their differences?
Your colleague writes
f = open("orders.txt", "w")every time a new order arrives, thenf.write(order). Why do the earlier orders disappear, and which mode should they use instead?If a file is opened in append mode, what happens to the file’s existing concents?
What does the following code display:
try: x = float('abc123') print('Conversion is complete.') except OSError: print('Code caused an IOError.') except ValueError: print('Code caused a ValueError.') print('End.')What is the difference between the two approaches? Which one is preferred in Python?
import re def is_integer(s: str) -> bool: """Return True if s is a string representing an integer, e.g. "42" or "-7".""" return re.fullmatch(r"[+-]?[0-9]+", s) is not None while not is_integer(order_count_str := input("Enter order count: ")): print("You did not enter a number. Try again.") order_count = int(order_count_str) # process order ...def input_order_count() -> int: while True: order_count_str = input("Enter order count: ") try: order_count = int(order_count_str) except ValueError: print("You did not enter a number. Try again.") else: return order_count order_count = input_order_count() # process orderWhy should you prefer with
open(...) as f:over callingf.close()yourself? What happens if an exception occurs between open and close?