0
0
Pythonprogramming~5 mins

Writing multiple lines in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Awith open(filename, 'w') as file:
Bopen(filename, 'w')
Cfile.close()
Dwrite(filename)
What does writelines() do when writing multiple lines?
AAdds newlines automatically between lines
BWrites a list of strings without adding newlines
CWrites a single string with newlines
DCloses the file after writing
How do you add a newline after each line when writing multiple lines with a loop?
AAdd '\n' at the end of each string
BUse <code>write()</code> without changes
CUse <code>writelines()</code> only
DCall <code>file.newline()</code>
Which mode should you use to write multiple lines to a new file?
A'a' mode
B'r' mode
C'w' mode
D'x' mode
What happens if you forget to close a file after writing multiple lines?
ANothing happens
BFile is deleted
CFile opens automatically next time
DData may not be saved properly
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.