0

I come across the task to save files on my server (Max file size is 10 mb) and found this answer. This works perfectly, but I'm wondering what is the point to use shutil module and what is the difference between:

file_location = f"files/{uploaded_file.filename}"
with open(file_location, "wb+") as file_object:
    file_object.write(uploaded_file.file.read())

vs

import shutil

file_location = f"files/{uploaded_file.filename}"
with open(file_location, "wb+") as file_object:
    shutil.copyfileobj(uploaded_file.file, file_object) 

During my programming experience, I was coming across with shutil module multiple times but still can't find out the benefits of one more import.

salius
  • 588
  • 3
  • 17

1 Answers1

4

Your method requires the whole file be in memory. shutil copies in chunks so you can copy files larger than memory. Also, shutil has routines to copy files by name so you don't have to open them at all, and it can preserve the permissions, ownership, and creation/modification/access timestamps.

Tim Roberts
  • 34,376
  • 3
  • 17
  • 24