Skip to content

Instantly share code, notes, and snippets.

@cshirky
Last active December 30, 2015 11:59
Show Gist options
  • Save cshirky/7826245 to your computer and use it in GitHub Desktop.
Save cshirky/7826245 to your computer and use it in GitHub Desktop.
Convert files form command line or all files in a dir to Base64. In Dir mode, also builds an archive of all converted files, one per line, preceded by filename:
#!/usr/bin/env python
### Convert jpg, png and gif files in a directory to Base64
### Append the data to a master file in the format 'original_filename.jpg:Base64 data'
import os, base64, sys
ARCHIVE = True
if (ARCHIVE):
a = open("file_archive.b64", 'a+')
def convert_to_b64(f):
with open(f) as stream:
encoded = base64.b64encode(stream.read())
o = open(f+".b64", 'w+')
o.write(encoded)
if (ARCHIVE):
print "Writing "+f
a.write(f+":"+encoded)
def file_list():
try:
f = sys.argv[1]
print "Looking at "+f
ARCHIVE = False
convert_to_b64(f)
except:
files = os.listdir(".")
for f in files:
if not f.endswith('b64') and f+".b64" not in files:
print 'Looking at '+f
convert_to_b64(f)
file_list()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment