I have two methods for writing binary files: the first works with data received by a server corresponding to a file upload (i.e., handling a form whose enctype="multipart/form-data"), and the second works with file data sent as email attachments (i.e., file data obtained by parsing an email message message body using get_payload()).
The odd thing is, they're not interchangeable: if I use the first one to save data parsed from an email attachment, it fails; similarly, the second function fails when dealing with uploaded file data.
What are the critical differences?
This is the first method:
def write_binary_file (folder, filename, f, chunk_size=4096):
"""Write the file data f to the folder and filename combination"""
result = False
if confirm_folder(folder):
try:
file_obj = open(os.path.join(folder, file_base_name(filename)), 'wb', chunk_size)
for file_chunk in read_buffer(f, chunk_size):
file_obj.write(file_chunk)
file_obj.close()
result = True
except (IOError):
print "file_utils.write_binary_file: could not write '%s' to '%s'" % (file_base_name(filename), folder)
return result
This is the second method:
def write_binary_file (folder, filename, filedata):
"""Write the binary file data to the folder and filename combination"""
result = False
if confirm_folder(folder):
try:
file_obj = open(os.path.join(folder, file_base_name(filename)), 'wb')
file_obj.write(filedata)
file_obj.close()
result = True
except (IOError):
print "file_utils.write_binary_file: could not write '%s' to '%s'" % (file_base_name(filename), folder)
return result