Bird
0
0

Which of the following Python code snippets correctly appends the string 'Hello' to a file named greetings.txt?

easy📝 Syntax Q3 of 15
Python - File Handling Fundamentals
Which of the following Python code snippets correctly appends the string 'Hello' to a file named greetings.txt?
Awith open('greetings.txt', 'w') as f: f.write('Hello')
Bwith open('greetings.txt', 'a') as f: f.write('Hello')
Cwith open('greetings.txt', 'r') as f: f.write('Hello')
Dwith open('greetings.txt', 'x') as f: f.write('Hello')
Step-by-Step Solution
Solution:
  1. Step 1: Choose the correct mode for appending

    Mode 'a' opens the file for appending without deleting existing content.
  2. Step 2: Confirm the write operation is allowed

    Mode 'a' allows writing, so f.write('Hello') works correctly.
  3. Final Answer:

    with open('greetings.txt', 'a') as f:\n f.write('Hello') -> Option B
  4. Quick Check:

    Append mode with write = correct [OK]
Quick Trick: Use 'a' mode with write() to add text [OK]
Common Mistakes:
  • Using 'w' which overwrites file
  • Using 'r' which is read-only
  • Using 'x' which errors if file exists

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes