The file has current position at which read, write is performed. Initially the file position is at the beginning (unless you opened the file with append move (a
) or you moved file position explicitly).
File position is advanced if you write/read accordingly. If you don't rewind the file, you will get empty string if you read from there. Using file.seek
, you can move the file position.
with tempfile.TemporaryFile(suffix=".png") as tmpfile:
fig.savefig(tmpfile, format="png") # File position is at the end of the file.
tmpfile.seek(0) # Rewind the file. (0: the beginning of the file)
print b64encode(tmpfile.read())