Python: binary file to gz file and then to jpg extension and finally return again to the original binary file
Question: I want to do the following in Python:

  1. Take a binary (executable) file
  2. Turn it into a zip file with gzip (gz extension)
  3. Then put the jpg extension

Later again the desire to recover the original (without the gz extension or
jpg).

The idea is to send binary files through GMail SMTP to recover and then get
them over IMAP and process them in ehtir original form (1).


Answer: You can use [`gzip`](http://docs.python.org/library/gzip.html) to compress the
files and
[`os.rename`](http://docs.python.org/library/os.html?highlight=os.rename#os.rename)
to change file names. In your case you could just use `gzip` and save it with
a `.jpg` extension in the first place.

    
    
    import gzip
    
    # write compressed file
    with gzip.open('my_file.jpg', 'wb') as f:
        f.write(content)
    
    # read it again
    with gzip.open('my_file.jpg', 'rb') as f:
        content = f.read()
    

