Presistence Storage
Presistence Storage
after the program has stopped running. Here are some common methods and modules used to
implement persistence:
1. Using Files
Text Files: Basic read and write operations to store data in a text format.
Binary Files: Use binary mode to store data in a more compact or complex format.
Example
data = file.read()
print(data)
Explination
with open("data.txt", "w"): This line opens (or creates if it doesn’t exist) a file named data.txt in
write mode ("w").
file.write("Some persistent data"): This writes the string "Some persistent data" into the file.
The with statement ensures the file is properly closed after writing, even if an error occurs.
"r" mode is for reading only. An error occurs if the file doesn’t exist.
data = file.read(): Reads the contents of the file and stores it in the variable data.
2. Pickle Module
The pickle module serializes Python objects (e.g., lists, dictionaries, classes) into a byte stream and
saves it to a file. It can later deserialize this stream back into the original object.
Example
import pickle
# Saving data
pickle.dump(data, file)
# Loading data
loaded_data = pickle.load(file)
print(loaded_data)
explination
Creating data:
o The code creates a Python dictionary data with keys 'name' and 'age', representing a
person’s name and age.
Opening data.pkl:
o open("data.pkl", "wb") opens (or creates) a file named data.pkl in write binary mode
("wb").
o The wb mode allows writing binary data to the file, which is necessary for pickle.
pickle.dump(data, file):
o The dump function requires the object to be saved (data) and the file to write it to
(file).
When this part of the code runs, data.pkl will store the serialized dictionary in a binary format.
Opening data.pkl:
open("data.pkl", "rb") opens the file in read binary mode ("rb"), which is needed to read
binary data.
pickle.load(file):
This function reads and deserializes the binary data from data.pkl, converting it back into the
original Python dictionary.
Printing loaded_data:
print(loaded_data) outputs the dictionary content, showing {'name': 'Alice', 'age': 25}.
3. JSON Module
The json module is useful for saving data in JSON format, which is a common, human-readable data
interchange format. JSON works well for dictionaries and lists with simple data types (strings,
numbers).
Example
import json
# Saving data
json.dump(data, file)
# Loading data
loaded_data = json.load(file)
print(loaded_data)
explination
This code demonstrates how to use the json module in Python to save and load data in JSON format.
JSON (JavaScript Object Notation) is a popular, human-readable data format that's ideal for simple
data structures like dictionaries and lists. Here’s a step-by-step breakdown of each part:
json module provides methods to serialize (convert) Python objects to JSON format and deserialize
JSON data back into Python objects.
Creating data:
The code creates a dictionary data with keys 'name' and 'age', representing a person's name
and age.
Opening data.json:
open("data.json", "w") opens (or creates if it doesn’t exist) a file named data.json in write
mode ("w").
"w" mode means that the file will be overwritten if it already exists.
json.dump(data, file):
This converts data to JSON format (a string format similar to a Python dictionary but in JSON
syntax) and saves it to the file.
Loading Data with json.load() opens the file in read mode ("r") to fetch the saved JSON data.
json.load() reads and deserializes the JSON data from the file, converting it back into a Python
dictionary.
4. Shelve Module
The shelve module is like a persistent dictionary that allows to store objects by key. It uses pickle
internally, making it suitable for more complex data.
import shelve
# Storing data
db['name'] = 'Alice'
db['age'] = 25
# Retrieving data
print(db['name']) # Alice
print(db['age']) # 25
Explination
The shelve module provides a way to store persistent data on disk with a syntax similar to Python
dictionaries, making it easy to save and access data by key.
This line opens (or creates if it doesn’t exist) a persistent dictionary called "data_shelve".
The open function in shelve works like opening a file but returns a dictionary-like object
(called db in this case) that allows data to be saved with key-value pairs.
By default, shelve.open() creates a few additional files to manage the stored data, usually
with extensions like .dat, .bak, or .dir, depending on the operating system.
This line re-opens the data_shelve file in read/write mode, enabling access to the stored
data.
Accessing Data:
db['name'] retrieves the value associated with the key 'name', which is 'Alice'.
db['age'] retrieves the value associated with the key 'age', which is 25.
Once again, the with statement ensures db is automatically closed when done, making sure
no data is left unsaved.
5. SQLite Database
The sqlite3 module provides an embedded SQL database. It is highly suitable for more structured
data storage with relational properties.
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# Create a table
# Insert data
conn.commit()
# Retrieve data
print(cursor.fetchall())
# Close connection
conn.close()
Explination
Database Connection: sqlite3.connect() establishes a connection and creates the database file if it
doesn’t exist.
Resource Management: conn.close() ensures the database connection is properly closed when
done.