Bird
0
0

You want to write multiple lines from a list lines = ['First', 'Second', 'Third'] to a file so each line appears on its own line in the file. Which code correctly does this?

hard📝 Application Q15 of 15
Python - File Handling Fundamentals
You want to write multiple lines from a list lines = ['First', 'Second', 'Third'] to a file so each line appears on its own line in the file. Which code correctly does this?
Awith open('out.txt', 'w') as f: f.writelines(lines)
Bwith open('out.txt', 'w') as f: f.write(lines)
Cwith open('out.txt', 'w') as f: f.write('\n'.join(lines))
Dwith open('out.txt', 'w') as f: for line in lines: f.write(line + '\n')
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to write lines with newlines

    Each line must end with a newline character '\n' to appear on separate lines in the file.
  2. Step 2: Evaluate each option

    with open('out.txt', 'w') as f: for line in lines: f.write(line + '\n') writes each line with '\n' explicitly, so lines appear separately. with open('out.txt', 'w') as f: f.write(lines) tries to write a list directly, which causes a TypeError. with open('out.txt', 'w') as f: f.write('\n'.join(lines)) joins lines with '\n' but does not add a final newline after the last line (which is acceptable but less explicit). with open('out.txt', 'w') as f: f.writelines(lines) uses writelines() but without adding '\n', so lines will run together.
  3. Final Answer:

    with open('out.txt', 'w') as f: for line in lines: f.write(line + '\n') -> Option D
  4. Quick Check:

    Add '\n' to each line when writing in loop [OK]
Quick Trick: Add '\n' to each line when writing in a loop [OK]
Common Mistakes:
  • Writing list directly without joining
  • Using writelines() without newlines
  • Forgetting '\n' causes lines to merge

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes