Last unit, we learned about dictionaries, which store data as key–value pairs. For example, we used names as keys and scores as values to quickly look up and update information. But there’s a problem, when the program ends, all the data in memory disappears. Now students try to finish the following practice to review what we learned last unit:
Output example:
Average score: 85.0
Top student: Cathy with 92
Answer example:
students = {"Alice": 88, "Bob": 75, "Cathy": 92}
avg = sum(students.values()) / len(students)
best_name = max(students, key=lambda n: students[n])
best_score = students[best_name]
print(f"Average score: {avg:.1f}")
print(f"Top student: {best_name} with {best_score}")
So, what if we want to keep that information for later use? That’s what we’ll learn today: files. Files give your programs memory, allowing them to remember and restore data even after you close them. In this unit, we’ll learn how to use open() and with open() to read from and write to files — giving our programs real, lasting memory.