Malformed file when downloading xlsx file with python sdk

Got an interesting question from a developer:

I am accessing box to download an xlsx file, the file gets downloaded, yet it is corrupted, may you help ? thanks in advance

file_id = '1234'

download_file = client.file(file_id).get()
transfer_file = open("/home/wsuser/work/" + download_file.name, 'wb')
download_file.download_to(transfer_file)

Hi Massimo,

Python open does not close the file automatically, and I suspect it is why your file is getting corrupted.

Try it like this:

file_id = '1234'

download_file = client.file(file_id).get()
with open("/home/wsuser/work/" + download_file.name, 'wb') as transfer_file:
    download_file.download_to(transfer_file)

The with statement will close the file once the download is done.