Created
October 21, 2011 15:53
-
-
Save zed/1304181 to your computer and use it in GitHub Desktop.
store multiple images in a single file using sqlite3 in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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