5. You want to append multiple lines from a list lines = ['First line', 'Second line', 'Third line'] to a file output.txt, each on a new line. Which code correctly does this?
hard
A. with open('output.txt', 'a') as f:
for line in lines:
f.write(line + '\n')
B. with open('output.txt', 'w') as f:
for line in lines:
f.write(line + '\n')
C. with open('output.txt', 'a') as f:
f.write(lines)
D. with open('output.txt', 'a') as f:
f.writelines(lines)
Solution
Step 1: Choose correct mode for appending
Mode 'a' appends data without erasing existing content; 'w' overwrites.
Step 2: Write each line with newline
Looping over lines and writing each with '\n' ensures each line is on a new line.
Step 3: Check other options
with open('output.txt', 'a') as f:
f.write(lines) tries to write list directly (error), writelines(lines) writes lines without newlines, the 'w' mode option overwrites file.
Final Answer:
with open('output.txt', 'a') as f:
for line in lines:
f.write(line + '\n') -> Option A
Quick Check:
Append mode + loop + add '\n' = correct [OK]
Hint: Loop and add '\n' when appending multiple lines [OK]