Bird
0
0

You want to copy contents from source.txt to dest.txt safely, ensuring both files close properly even if an error occurs. Which code correctly uses a single with statement to handle both files?

hard📝 Application Q15 of 15
Python - Context Managers
You want to copy contents from source.txt to dest.txt safely, ensuring both files close properly even if an error occurs. Which code correctly uses a single with statement to handle both files?
Awith open('source.txt') as src and open('dest.txt', 'w') as dst: dst.write(src.read())
Bwith open('source.txt') as src, open('dest.txt', 'w') as dst: dst.write(src.read())
Cwith open('source.txt') as src: with open('dest.txt', 'w') as dst: dst.write(src.read())
Dsrc = open('source.txt') dst = open('dest.txt', 'w') dst.write(src.read()) src.close() dst.close()
Step-by-Step Solution
Solution:
  1. Step 1: Understand safe resource handling

    Using a single with statement with multiple resources ensures all files close properly even if errors happen.
  2. Step 2: Evaluate options

    with open('source.txt') as src, open('dest.txt', 'w') as dst: dst.write(src.read()) uses one with with two files separated by a comma, correctly handling both. src = open('source.txt') dst = open('dest.txt', 'w') dst.write(src.read()) src.close() dst.close() manually closes files (less safe). with open('source.txt') as src: with open('dest.txt', 'w') as dst: dst.write(src.read()) uses nested with (correct but not single with). with open('source.txt') as src and open('dest.txt', 'w') as dst: dst.write(src.read()) uses invalid syntax with 'and'.
  3. Final Answer:

    with open('source.txt') as src, open('dest.txt', 'w') as dst: dst.write(src.read()) -> Option B
  4. Quick Check:

    Single with with commas = D [OK]
Quick Trick: Use commas inside one with to open multiple files [OK]
Common Mistakes:
  • Using nested with instead of single
  • Forgetting to close files manually
  • Using invalid syntax like 'and' in with

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes