§ 02 — Integrative Programming and Technologies 1
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.
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.
Pro3 reviewers locked
Part of this subject's paid reviewers. Not included in this printout.
Done with this module? Track it — your progress shows on the subject list.
Studying with blockmates? Send them this lesson.
Up next
Lesson 6: Python Refresher — Integrating Python with Technologies→←Previous: Lesson 4: Python Refresher — Lists, Tuples, and Dictionaries