Bird
0
0

Given a list lines = ['Apple', 'Banana', 'Cherry'], which code snippet correctly writes each item on a separate line in a file named fruits.txt?

hard📝 Application Q8 of 15
Python - File Handling Fundamentals
Given a list lines = ['Apple', 'Banana', 'Cherry'], which code snippet correctly writes each item on a separate line in a file named fruits.txt?
Awith open('fruits.txt', 'w') as f: for item in lines: f.write(item + '\n')
Bwith open('fruits.txt', 'w') as f: f.write(str(lines))
Cwith open('fruits.txt', 'w') as f: f.writelines(lines)
Dwith open('fruits.txt', 'w') as f: f.write('\n'.join(lines))
Step-by-Step Solution
Solution:
  1. Step 1: Open the file in write mode

    Using with open('fruits.txt', 'w') ensures the file is opened for writing and closed automatically.
  2. Step 2: Write each line with a newline character

    Iterate over each item in lines and write it followed by \n to ensure each appears on its own line.
  3. Final Answer:

    Each list item is written on a separate line by adding '\n' explicitly. -> Option A
  4. Quick Check:

    Check for explicit newline after each item [OK]
Quick Trick: Write each line with '\n' to separate lines [OK]
Common Mistakes:
  • Using writelines() without adding newline characters
  • Writing the list directly as a string
  • Joining lines without writing to file properly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes