Python
/
Storage
- 1 Language 9
-
Hello World
-
Variables
-
Functions
-
Conditional
-
Operators
-
While
-
Turtle
-
Script Mode
-
Debugging
- 2 Strings 6
-
Slice
-
Raw Strings
-
Regex
-
Validation
-
Config
-
Escape
- 3 Collections 5
-
Lists
-
Dictionaries
-
Efficiency
-
Tuples
-
References
- 4 Functions 5
-
Recursion
-
Factorial
-
Modulus
-
Reassignment
-
Approximate
- 5 Storage 8
-
Files
-
Databases
-
Pipes
-
With open
-
Shelve
-
Zip
-
Csv
-
Json
- 6 Class 4
-
Definition
-
Attributes
-
Functional
-
Methods
- 7 Goodies 5
-
Conditional Expression
-
List Comprehension
-
Generator
-
Named Tuple
-
Modules
- 8 Applications 5
-
Pythagora
-
Palindrome
-
Binary Search
-
Conway Game
-
Coin Flip
- 9 Scheduler 4
-
Time
-
Multithreading
-
Subprocess
-
Logging
- 10 Packages 2
-
Clipboard
-
Ocr
/
Databases
➟
➟
Last update: 19-11-2021
Dbm
p252 ! A database is a file for storing data.
# Many databases are like dictionaries (map keys to values).
# The biggest difference is that the database is on disk.
import os
import dbm
DIR = os.path.dirname(os.path.realpath(__file__))
IMAGES_DB = DIR + "/db/images_db"
db = dbm.open(IMAGES_DB, 'c')
db['myimage.jpg'] = '/images/myimage.jpg'
db['myimage.png'] = '/images/myimage.png'
print(db['myimage.jpg'])
# b'/images/myimage.jpg'
# the result is a bytes object (it begins with b)
db.close()
# You can use dictionaries methods ...
# to loop through items.
db = dbm.open(IMAGES_DB)
for key in db.keys():
print(key, db[key])
# b'myimage.png' b'/images/myimage.png'
# b'myimage.jpg' b'/images/myimage.jpg'
db.close()
Pickle
! With pickle module you can store any type.
# Pickle storage:
#
# Databases have a limitation ...
# they works only with strings or bytes.
#
# With pickle module you can convert and store any type.
import os
import dbm
import pickle
DIR = os.path.dirname(os.path.realpath(__file__))
IMAGES_DB = DIR + "/db/images_db_pickle"
# Write
# -------------------------------------------
db = dbm.open(IMAGES_DB, 'c')
t = [1, 2, 3]
str = pickle.dumps(t) # b'\x80\x03]q\x00(K\x01K\x02K\x03e.'
db['mylist'] = str
db.close()
# Read
# -------------------------------------------
db = dbm.open(IMAGES_DB, 'r')
b = db['mylist']
str = pickle.loads(b)
assert str == [1, 2, 3]
db.close()
# Object copy
#
# Pickle then revers ....
# has the same effect as copying the object.
#-------------------------------------------
t1 = (1, 2, 3)
str = pickle.dumps(t1)
t2 = pickle.loads(str)
assert t2 == (1, 2, 3)
assert t1 == t2
assert (t1 is t2) == False
# Shelf:
#
# In a 'shelf' db the values can be any objects that pickle can handle.
# --------------------------------------------
import shelve
IMAGES_DB = DIR + "/db/images_db_shelf"
t = (1, 2, 3)
db = shelve.open(IMAGES_DB, 'c')
db['my_tuple'] = t
db.close()
db = shelve.open(IMAGES_DB, 'w')
assert db['my_tuple'] == (1, 2, 3) # pass
db.close()
➥ Questions github Storage