string - How to convert fileData from str to file type in Python? -
i've got file data read api base64 , converted regular file data using following:
base64filedata = attachmentobj.data['data'] filedata = base64.urlsafe_b64decode(base64filedata.encode('utf-8')) print type(filedata) # prints out <type 'str'>
since need file in binary further process it, can store , read out follows:
print type(filedata) # prints out <type 'str'> open('thefile.pdf', 'w') f: f.write(filedata) open('thefile.pdf', 'rb') f: print type(f) # prints out <type 'file'>, need.
this works, seeing there no need store file, seems 1 of worst pieces of code i've ever seen.
does know how can convert initial filedata type 'file'
without storing , reading out? tips welcome!
check out stringio / cstringio modules. present file interface existing buffer (string) in memory. let pass data library without writing temp file.
for example:
import stringio ... base64filedata = attachmentobj.data['data'] filedata = base64.urlsafe_b64decode(base64filedata.encode('utf-8')) memoryfile = stringio.stringio(filedata) somefunctionthatoperatesonfileobjects(memoryfile)
Comments
Post a Comment