5 questions to test your understanding
A file named 'data.txt' contains the text 'Hello World'. A program opens it with open('data.txt', 'w') and writes 'Goodbye'. What does the file contain after the program finishes?
A file contains the line '42'. After reading it with line = f.readline(), a student writes result = line + 10. What happens?
Using a context manager (with open(...) as f:) guarantees that the file is closed even if an exception occurs inside the with block.
Forgetting to close a file after writing is a minor stylistic issue; most written data will be saved correctly as long as the write() calls completed without error.
Explain the difference between opening a file in 'w' mode versus 'a' mode. Why is confusing these two modes particularly dangerous?