{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Pickle" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pickle\n", "class StudentObject:\n", " def __init__(self):\n", " pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using `pickle` to write multiple records\n", "- input a student record and save it to a new serial file\n", "- read a student record from that file\n", "- extend your program to work for more than one record" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "John born on 2025-03-04 15:15:35.959676, full time is yes\n", "John born on 2025-03-04 15:14:04.842286, full time is yes\n", "Jake born on 2025-03-04 15:14:04.842378, full time is yes\n" ] } ], "source": [ "import datetime\n", "import pickle\n", "DATA_FILENAME = \"student_data.dat\"\n", "class Student:\n", " def __init__(self, name, dob):\n", " self.__Name = name\n", " self.__DateOfBirth = dob\n", " self.__FullTime = True\n", " def GetName(self):\n", " return self.__Name\n", " def __str__(self):\n", " return f\"{self.__Name} born on {self.__DateOfBirth}, full time is {'yes' if self.__FullTime else 'nah'}\"\n", "def write_to_file(obj):\n", " with open(DATA_FILENAME, 'ab+') as file:\n", " pickle.dump(obj, file)\n", " file.close()\n", "def read_from_file():\n", " with open(DATA_FILENAME, 'rb') as file:\n", " s1 = pickle.load(file)\n", " s2 = pickle.load(file)\n", " file.close()\n", " print(s1)\n", " print(s2)\n", "s1 = Student(\"John\", datetime.datetime.now())\n", "s2 = Student(\"Jake\", datetime.datetime.now())\n", "s3 = Student(\"Jaguar\", datetime.datetime.now())\n", "s4 = Student(\"Jack\", datetime.datetime.now())\n", "s5 = Student(\"Jacqueline\", datetime.datetime.now())\n", "s6 = Student(\"Jiashuo\", datetime.datetime.now())\n", "print(s1)\n", "write_to_file(s1)\n", "write_to_file(s2)\n", "write_to_file(s3)\n", "read_from_file()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Activity 20M, with pickles" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.7" } }, "nbformat": 4, "nbformat_minor": 2 }