Recall & Review
beginner
What is the purpose of the
open() function in Python?The
open() function is used to open a file so you can read from it, write to it, or both. It returns a file object that you can work with.Click to reveal answer
beginner
What does the mode parameter in
open(filename, mode) specify?The mode parameter tells Python how you want to use the file: <br> -
'r' for reading <br> - 'w' for writing (overwrites file) <br> - 'a' for appending (adding to the end) <br> - 'b' for binary mode <br> - You can combine modes like 'rb' for reading binary files.Click to reveal answer
beginner
Why is it important to close a file after opening it?
Closing a file frees up system resources and ensures that all data is properly saved and written. If you don't close a file, changes might not be saved and the file can stay locked.
Click to reveal answer
beginner
How do you properly close a file in Python?
You call the
close() method on the file object, like file.close(). This tells Python you are done working with the file.Click to reveal answer
intermediate
What is the advantage of using the
with statement when working with files?Using
with open(filename) as file: automatically closes the file when the block ends, even if errors happen. This makes your code safer and cleaner.Click to reveal answer
Which mode should you use to open a file for reading only?
✗ Incorrect
The mode 'r' opens the file for reading only.
What happens if you open a file in 'w' mode and the file already exists?
✗ Incorrect
Opening in 'w' mode erases existing content and starts fresh.
Which method do you call to close a file?
✗ Incorrect
The method to close a file is close().
What is the benefit of using
with open() instead of just open()?✗ Incorrect
Using with open() ensures the file is closed automatically.
If you want to add text to the end of an existing file without deleting its content, which mode do you use?
✗ Incorrect
Mode 'a' opens the file for appending, adding text at the end.
Explain how to open a file for reading and then close it properly in Python.
Think about the steps: open, use, then close.
You got /4 concepts.
Describe the advantages of using the
with statement when working with files.Why is 'with' safer than just open()?
You got /4 concepts.