Recall & Review
beginner
What Python function is used to open a file for reading or writing?
The
open() function is used to open a file. You can specify the mode like 'r' for reading or 'w' for writing.Click to reveal answer
beginner
What does the mode 'r' mean when opening a file?
Mode 'r' means open the file for reading only. The file must exist or Python will give an error.
Click to reveal answer
beginner
How do you properly close a file after opening it?
You call the
close() method on the file object, like file.close(). This frees system resources.Click to reveal answer
intermediate
What is the advantage of using a
with statement when working with files?Using
with automatically closes the file when the block ends, even if errors happen. It keeps code safe and clean.Click to reveal answer
beginner
How do you write text to a file in Python?
Open the file in write mode ('w'), then use
file.write('your text') to add text. Remember to close the file or use with.Click to reveal answer
Which mode opens a file for appending data without deleting existing content?
✗ Incorrect
Mode 'a' opens the file for appending. It adds new data at the end without removing existing content.
What happens if you try to open a non-existent file in 'r' mode?
✗ Incorrect
Opening a file in 'r' mode requires the file to exist. If it doesn't, Python raises a FileNotFoundError.
Which method reads the entire content of a file as a string?
✗ Incorrect
The read() method reads all the content from the file and returns it as a string.
Why is it better to use 'with open(...) as file:' instead of just open()?
✗ Incorrect
Using 'with' ensures the file is closed automatically, even if errors occur, preventing resource leaks.
What does the 'w' mode do when opening a file?
✗ Incorrect
Mode 'w' opens the file for writing and erases any existing content before writing.
Explain how to safely read the contents of a text file in Python.
Think about how to open, read, and close a file safely.
You got /4 concepts.
Describe the difference between 'w' and 'a' modes when opening a file.
Consider what happens to existing content in each mode.
You got /4 concepts.