Bird
0
0

You want to append a dictionary's keys and values as lines to a file data.txt in the format key:value\n. Which code snippet correctly does this?

hard📝 Application Q9 of 15
Python - File Handling Fundamentals
You want to append a dictionary's keys and values as lines to a file data.txt in the format key:value\n. Which code snippet correctly does this?
Awith open('data.txt', 'a') as f: for k, v in my_dict.items(): f.write(f'{k}:{v}\n')
Bwith open('data.txt', 'w') as f: for k, v in my_dict.items(): f.write(f'{k}:{v}\n')
Cwith open('data.txt', 'a') as f: f.write(str(my_dict))
Dwith open('data.txt', 'r') as f: for k, v in my_dict.items(): f.write(f'{k}:{v}\n')
Step-by-Step Solution
Solution:
  1. Step 1: Use append mode to add data without erasing

    Mode 'a' appends new lines to the file.
  2. Step 2: Loop through dictionary items and write formatted lines

    Writing each key:value pair with newline correctly appends data.
  3. Final Answer:

    with open('data.txt', 'a') as f:\n for k, v in my_dict.items():\n f.write(f'{k}:{v}\n') -> Option A
  4. Quick Check:

    Append mode + loop write = correct format [OK]
Quick Trick: Loop dict items and write lines in append mode [OK]
Common Mistakes:
  • Using 'w' mode which overwrites
  • Writing dict as string directly
  • Using 'r' mode which is read-only

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes