Recall & Review
beginner
How do you write multiple lines of text to a file in Python?
You can open a file in write mode and use a loop or write a list of lines using
writelines() method.Click to reveal answer
beginner
What does the
with statement do when writing to a file?It automatically opens the file and closes it after the block finishes, even if errors happen. This helps avoid forgetting to close the file.
Click to reveal answer
beginner
How can you write multiple lines using a loop?
You can loop over a list of strings and write each line with
file.write(line) inside the loop.Click to reveal answer
intermediate
What is the difference between
write() and writelines()?write() writes a single string. writelines() writes a list of strings but does not add newlines automatically.Click to reveal answer
beginner
Why should you add newline characters when writing multiple lines?
Because
writelines() does not add newlines, you must add \n at the end of each line to separate lines in the file.Click to reveal answer
Which Python statement ensures a file is properly closed after writing multiple lines?
✗ Incorrect
The
with statement opens the file and automatically closes it after the block.What does
writelines() do when writing multiple lines?✗ Incorrect
writelines() writes all strings in the list as is, so you must add newlines yourself.How do you add a newline after each line when writing multiple lines with a loop?
✗ Incorrect
You must add '\n' to each string to create new lines in the file.
Which mode should you use to write multiple lines to a new file?
✗ Incorrect
'w' mode opens the file for writing and creates it if it doesn't exist.
What happens if you forget to close a file after writing multiple lines?
✗ Incorrect
Not closing a file can cause data loss because buffers may not flush to disk.
Explain how to write multiple lines to a file in Python using a loop and the
with statement.Think about opening the file safely and writing each line one by one.
You got /5 concepts.
Describe the difference between
write() and writelines() when writing multiple lines.Focus on how each method handles strings and newlines.
You got /4 concepts.