0% found this document useful (0 votes)
3 views5 pages

Presistence Storage

The document explains various methods for implementing persistent storage in Python, including using text and binary files, the pickle module for object serialization, the JSON module for human-readable data formats, the shelve module for key-value storage, and the sqlite3 module for structured database storage. Each method is accompanied by code examples and detailed explanations of how to save and retrieve data. These techniques allow data to be stored and accessed even after the program has stopped running.

Uploaded by

rj0110865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views5 pages

Presistence Storage

The document explains various methods for implementing persistent storage in Python, including using text and binary files, the pickle module for object serialization, the JSON module for human-readable data formats, the shelve module for key-value storage, and the sqlite3 module for structured database storage. Each method is accompanied by code examples and detailed explanations of how to save and retrieve data. These techniques allow data to be stored and accessed even after the program has stopped running.

Uploaded by

rj0110865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

In Python, persistent storage refers to saving data in a way that it can be retrieved and used even

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

# Writing to a text file

with open("data.txt", "w") as file:

file.write("Some persistent data")

# Reading from a text file

with open("data.txt", "r") as file:

data = file.read()

print(data)

Explination

demonstrates how to write to and read from a text file in Python

 with open("data.txt", "w"): This line opens (or creates if it doesn’t exist) a file named data.txt in
write mode ("w").

 "w" mode will overwrite the file if it already exists.

 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.

 with open("data.txt", "r"): Opens data.txt in read mode ("r").

 "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.

 print(data): Prints the content of data to the console.

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

data = {'name': 'Alice', 'age': 25}

with open("data.pkl", "wb") as file:

pickle.dump(data, file)

# Loading data

with open("data.pkl", "rb") as file:

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 This function serializes the data dictionary and writes it to data.pkl.

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.

Loading Data with pickle.load()

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.

 The deserialized object is stored in loaded_data.

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

data = {'name': 'Alice', 'age': 25}

with open("data.json", "w") as file:

json.dump(data, file)

# Loading data

with open("data.json", "r") as file:

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.

Saving Data with json.dump()

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):

 json.dump() serializes the data dictionary and writes it to data.json.

 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.

The deserialized data is stored in the variable loaded_data.

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

with shelve.open("data_shelve") as db:

db['name'] = 'Alice'

db['age'] = 25

# Retrieving data

with shelve.open("data_shelve") as db:

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.

Storing Data- shelve.open("data_shelve"):

 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.

Retrieving Data-  Re-opening data_shelve:

 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.

 These values are then printed.


 Closing the Shelf:

 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

# Connect to the database (or create if it doesn't exist)

conn = sqlite3.connect('example.db')

cursor = conn.cursor()

# Create a table

cursor.execute('''CREATE TABLE IF NOT EXISTS users (name TEXT, age INTEGER)''')

# Insert data

cursor.execute("INSERT INTO users VALUES ('Alice', 25)")

# Commit changes and close the connection

conn.commit()

# Retrieve data

cursor.execute("SELECT * FROM users")

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.

SQL Execution: cursor.execute() allows us to perform SQL operations.

Transactions: conn.commit() saves any changes made in the database.

Retrieving Data: cursor.fetchall() retrieves all results from a query.

Resource Management: conn.close() ensures the database connection is properly closed when
done.

You might also like