Skip to content

Instantly share code, notes, and snippets.

@tdicola
Created May 14, 2016 01:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save tdicola/e0ae6cb64c40f4ab888e90a16114d3b0 to your computer and use it in GitHub Desktop.
Save tdicola/e0ae6cb64c40f4ab888e90a16114d3b0 to your computer and use it in GitHub Desktop.
Files used in 'Raspberry Pi & Python basic data storage with Tony D!' live stream.
# Python Data Storage Demos Example 0: No Data Storage
# Basic setup for demos which show different ways to store program state (data)
# using standard and other Python libraries. This example has no data storage
# and will always show default values when run.
#
# Author: Tony DiCola
# License: Public Domain
# Create a class to represent a person and their favorite color.
class Person(object):
def __init__(self):
# Set name and favorite color to defaults.
self.name = 'No Name'
self.favorite_color = 'Black'
def load(self):
# Attempt to load the person state from some file/storage system.
# For now this is unimplemented!
pass
def save(self):
# Attempt to save the person state to a file/storage system.
# For now this is unimplemented!
pass
# Main program which creates a person and prompts with a menu to change their
# name or favorite color.
if __name__ == '__main__':
# Create a person instance and try to load any previous state.
person = Person()
person.load()
# Now run in a loop and allow the name and color to be changed.
while True:
# Print out a menu of options.
print('Hello {0}! Your favorite color is: {1}'.format(person.name, person.favorite_color))
print('Options:')
print(' 1 - Change name')
print(' 2 - Change favorite color')
print(' 3 - Quit')
option = input('Enter option: ')
# Check that the selected option is valid.
if option not in ('1', '2', '3'):
# Print an error and go back to the start of the loop.
print('Unknown option!')
continue
if option == '1':
# Change person's name.
person.name = input('New name: ')
elif option == '2':
# Change person's favorite color:
person.favorite_color = input('Favorite color: ')
elif option == '3':
# Break out of the loop to exit.
print('Goodbye!')
break
# Once the main loop ends (by picking the quit option) save the person state.
person.save()
# Python Data Storage Demos Example 1: Pickle Module
# Persist a person object to disk using Python's pickle module for Python object
# persistence.
#
# Author: Tony DiCola
# License: Public Domain
import pickle
# Create a class to represent a person and their favorite color.
class Person(object):
def __init__(self):
# Set name and favorite color to defaults.
self.name = 'No Name'
self.favorite_color = 'Black'
def load(self):
# Attempt to load the person state from a person.pickle file.
try:
with open('person.pickle', 'rb') as person_file:
# Use pickle.load to convert the file data into a python object.
person = pickle.load(person_file)
# Now copy out the name and favorite color to this object instance.
self.name = person.name
self.favorite_color = person.favorite_color
except FileNotFoundError:
# Ignore file not found error, the default person class will be used.
pass
def save(self):
# Attempt to save the person state to a person.pickle file.
with open('person.pickle', 'wb') as person_file:
pickle.dump(self, person_file)
# Main program which creates a person and prompts with a menu to change their
# name or favorite color.
if __name__ == '__main__':
# Create a person instance and try to load any previous state.
person = Person()
person.load()
# Now run in a loop and allow the name and color to be changed.
while True:
# Print out a menu of options.
print('Hello {0}! Your favorite color is: {1}'.format(person.name, person.favorite_color))
print('Options:')
print(' 1 - Change name')
print(' 2 - Change favorite color')
print(' 3 - Quit')
option = input('Enter option: ')
# Check that the selected option is valid.
if option not in ('1', '2', '3'):
# Print an error and go back to the start of the loop.
print('Unknown option!')
continue
if option == '1':
# Change person's name.
person.name = input('New name: ')
elif option == '2':
# Change person's favorite color:
person.favorite_color = input('Favorite color: ')
elif option == '3':
# Break out of the loop to exit.
print('Goodbye!')
break
# Once the main loop ends (by picking the quit option) save the person state.
person.save()
# Python Data Storage Demos Example 2: configparser Module
# Persist a person object to disk using Python's configparser module that reads
# and writes .ini style configuration files.
#
# Author: Tony DiCola
# License: Public Domain
import configparser
# Create a class to represent a person and their favorite color.
class Person(object):
def __init__(self):
# Set name and favorite color to defaults.
self.name = 'No Name'
self.favorite_color = 'Black'
def load(self):
# Attempt to load the person state from a person.ini file.
try:
with open('person.ini', 'r') as person_file:
# Read the file with configparser
config = configparser.ConfigParser()
config.read_file(person_file)
# Now grab the name and favorite color as attributes from the
# 'Person' section of the config file.
self.name = config['Person']['name']
self.favorite_color = config['Person']['favorite_color']
except FileNotFoundError:
# Ignore file not found error, defaults will be used instead.
pass
def save(self):
# Attempt to save the person state to a person.ini file.
with open('person.ini', 'w') as person_file:
config = configparser.ConfigParser()
config['Person'] = { 'name': self.name,
'favorite_color': self.favorite_color }
config.write(person_file)
# Main program which creates a person and prompts with a menu to change their
# name or favorite color.
if __name__ == '__main__':
# Create a person instance and try to load any previous state.
person = Person()
person.load()
# Now run in a loop and allow the name and color to be changed.
while True:
# Print out a menu of options.
print('Hello {0}! Your favorite color is: {1}'.format(person.name, person.favorite_color))
print('Options:')
print(' 1 - Change name')
print(' 2 - Change favorite color')
print(' 3 - Quit')
option = input('Enter option: ')
# Check that the selected option is valid.
if option not in ('1', '2', '3'):
# Print an error and go back to the start of the loop.
print('Unknown option!')
continue
if option == '1':
# Change person's name.
person.name = input('New name: ')
elif option == '2':
# Change person's favorite color:
person.favorite_color = input('Favorite color: ')
elif option == '3':
# Break out of the loop to exit.
print('Goodbye!')
break
# Once the main loop ends (by picking the quit option) save the person state.
person.save()
# Python Data Storage Demos Example 3: CSV for time-series data
# Persist sensor readings over time to a CSV (comma-separated file). This is
# great for easily storing time-series data in a file that can be read by
# other programs (like graphing in a spreadsheet).
#
# Author: Tony DiCola
# License: Public Domain
import csv
import datetime
import random
import time
# Create a new sensor.csv file that will contain a set of randomly generated
# fake sensor readings.
with open('sensor.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
# Write a header row with the name of each column.
writer.writerow(['Time', 'Humidity (%)', 'Temperature (F)'])
# Now loop generating new fake sensor readings every second and writing them
# to the CSV file.
while True:
# Make some fake sensor data.
reading_time = datetime.datetime.now()
humidity = random.uniform(0, 100)
temperature = random.uniform(-32, 120)
# Print out the data and write to the CSV file.
print('Time: {0} Humidity: {1} Temperature: {2}'.format(reading_time, humidity, temperature))
writer.writerow([reading_time, humidity, temperature])
# Pause for a second and repeat.
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment