Skip to content

@zed /allessandro.py
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.