Bird
0
0

You want to copy a large binary file efficiently in Python without loading it all at once. Which code snippet is best?

hard📝 Application Q9 of 15
Python - File Reading and Writing Strategies
You want to copy a large binary file efficiently in Python without loading it all at once. Which code snippet is best?
Awith open('source.bin', 'rb') as src, open('dest.bin', 'wb') as dst: while chunk := src.read(4096): dst.write(chunk)
Bwith open('source.bin', 'rb') as src, open('dest.bin', 'wb') as dst: dst.write(src.read())
Cwith open('source.bin', 'r') as src, open('dest.bin', 'w') as dst: dst.write(src.read())
Dwith open('source.bin', 'rb') as src: data = src.readlines() with open('dest.bin', 'wb') as dst: dst.writelines(data)
Step-by-Step Solution
Solution:
  1. Step 1: Use binary mode and chunked reading

    Opening files in binary mode 'rb' and 'wb' is required for binary files. Reading in chunks avoids loading entire file.
  2. Step 2: Use a loop with walrus operator to read and write chunks

    This method reads 4096 bytes at a time and writes them, efficiently copying large files.
  3. Final Answer:

    with open('source.bin', 'rb') as src, open('dest.bin', 'wb') as dst: while chunk := src.read(4096): dst.write(chunk) -> Option A
  4. Quick Check:

    Efficient binary copy = B [OK]
Quick Trick: Copy large files in chunks with binary mode [OK]
Common Mistakes:
  • Reading whole file at once
  • Using text mode for binary files
  • Using readlines() on binary files
  • Not looping to copy chunks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes