Reading and Writing Files
Many programs need to save or load data from files (like lists of users, logs, etc.). In Python, you use open() to work with files. Example of writing to a file:
with open("data.txt", "w") as file:
file.write("Hello file!\n")
This code opens (or creates) data.txt for writing ("w" mode) and writes a line. Using with ensures the file closes automatically. To read:
with open("data.txt", "r") as file:
content = file.read()
print(content) # Displays the file's contents
Or read line by line with file.readline(). Common modes: "r" (read), "w" (write, overwrites), "a" (append). Always handle files carefully (closing after done) to avoid data loss. For interactive programs, you might read a CSV of prices, update values, then write the new CSV.
Handling Errors with Exceptions
User input or file operations can fail. Python uses try/except to handle errors gracefully. Example:
try:
x = int(input("Enter a number: "))
print("Reciprocal is", 1/x)
except ValueError:
print("That is not an integer!")
except ZeroDivisionError:
print("Cannot divide by zero!")
This code handles two error types: if conversion to int fails, or if the user enters 0. Without try/except, the program would crash. Using exceptions, you can catch errors and respond (like reprompt or show a message). In exams, demonstrating that you know to catch errors can boost your solution.
Module Summary
ProReviewer — locked
Drills, code labs, and full solutions.
Worked Example: Robust File Sum
ProReviewer — locked
Drills, code labs, and full solutions.
Practice & Exam Drills — Lesson 13
ProReviewer — locked
Drills, code labs, and full solutions.