Skip to content

Instantly share code, notes, and snippets.

@zed
Created October 21, 2011 15:53
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save zed/1304181 to your computer and use it in GitHub Desktop.
Save zed/1304181 to your computer and use it in GitHub Desktop.
store multiple images in a single file using sqlite3 in Python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob
import os
import sqlite3
# support both Python 2.x and 3.x
try: buffer = buffer
except NameError:
buffer = lambda x: x # on Python 3.x 'rb' mode already returns what we need
def U(literal_string):
if hasattr(literal_string, 'decode'):
return literal_string.decode('utf-8') # source code encoding
return literal_string
# open db
conn = sqlite3.connect('images.db')
conn.execute('''create table if not exists images (
path unique not null,
image blob
)''')
def genimages():
"""Generate example images."""
for pngpath in glob.iglob(os.path.expanduser(U('~/Pictures/*.png'))):
with open(pngpath, 'rb') as f:
yield pngpath, buffer(f.read())
# insert images
with conn: # insert all or nothing
conn.executemany('insert into images(path,image) values(?, ?)', genimages())
# print image paths
for path, in conn.execute('select path from images'):
print(path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment