Imagine you write a program that needs to save user data permanently. Why is file handling important for this?
Think about what happens to data when a program closes without saving.
File handling is needed to save data permanently on disk. Without it, data disappears when the program ends.
Look at this Python code that writes and reads a file. What will it print?
with open('test.txt', 'w') as f: f.write('Hello') with open('test.txt', 'r') as f: content = f.read() print(content)
The code writes 'Hello' to a file, then reads it back.
The code writes 'Hello' to 'test.txt' then reads and prints it, so output is 'Hello'.
What error will this code raise?
with open('nofile.txt', 'r') as f: data = f.read()
The code tries to open a file that does not exist.
Trying to read a file that does not exist raises FileNotFoundError.
Which statement best explains why file handling is essential for data persistence?
Think about what happens to data stored only in memory when the program stops.
Data in memory is lost when the program ends. Files let data be saved permanently on disk.
This code writes lines to a file. How many lines will the file have?
lines = ['First line\n', 'Second line\n', 'Third line\n'] with open('lines.txt', 'w') as f: for line in lines: f.write(line)
Each string in the list ends with a newline character.
Each string ends with '\n', so each write adds a new line. There are 3 lines total.