Questions: File I/O Basics

5 questions to test your understanding

Score: 0 / 5
Question 1 Multiple Choice

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'Hello WorldGoodbye' — the new content is appended to the existing content
B'Goodbye Hello World' — the new content is prepended
C'Goodbye' — opening in 'w' mode erases the file before any writing occurs
DAn error is raised because the file already exists
Question 2 Multiple Choice

A file contains the line '42'. After reading it with line = f.readline(), a student writes result = line + 10. What happens?

Aresult is the integer 52
Bresult is the string '4210'
CA TypeError is raised — you cannot add a string and an integer
Dresult is '42\n10' — the newline from readline is included
Question 3 True / False

Using a context manager (with open(...) as f:) guarantees that the file is closed even if an exception occurs inside the with block.

TTrue
FFalse
Question 4 True / False

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.

TTrue
FFalse
Question 5 Short Answer

Explain the difference between opening a file in 'w' mode versus 'a' mode. Why is confusing these two modes particularly dangerous?

Think about your answer, then reveal below.