pythonfileiofastapishutil

Python read/write vs shutil copy


I need to save files uploaded to my server (Max file size is 10MB) and found this answer, which works perfectly. However, I'm wondering what is the point of using the shutil module, and what is the difference between this:

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

and this:

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 came across shutil module multiple times, but still can't figure out what its benefits are over read() and write() methods.


Solution

  • 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.