Recall & Review
beginner
What is the basic Python command to open a file for writing?
Use
open('filename', 'w') to open a file for writing. The 'w' mode means write.Click to reveal answer
beginner
What happens if you open a file in write mode ('w') and the file already exists?
The existing file is cleared (emptied) before writing new data.
Click to reveal answer
beginner
How do you write a string to a file after opening it in write mode?
Use the
write() method, like file.write('Hello').Click to reveal answer
beginner
Why should you always close a file after writing?
Closing the file saves changes and frees system resources.
Click to reveal answer
beginner
What is a safer way to write to a file that automatically closes it?
Use a
with statement, like with open('file.txt', 'w') as f: which closes the file automatically.Click to reveal answer
What mode do you use to open a file for writing in Python?
✗ Incorrect
The 'w' mode opens a file for writing, creating it if it doesn't exist or clearing it if it does.
What does the
write() method do?✗ Incorrect
The
write() method writes a string to the file.What happens if you open a file in 'w' mode and the file already has content?
✗ Incorrect
Opening in 'w' mode erases existing content before writing.
Which Python statement ensures a file is closed automatically after writing?
✗ Incorrect
The
with statement automatically closes the file when done.Why is it important to close a file after writing?
✗ Incorrect
Closing saves the data and releases system resources.
Explain the steps to write text data to a file in Python.
Think about opening, writing, and closing.
You got /3 concepts.
What are the benefits of using the with statement when writing to files?
Consider safety and code clarity.
You got /3 concepts.