Python Forum
How to save and load data from files using pickle
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to save and load data from files using pickle
#1
Pickle is a great way to save and load files because it encode the data before storing it. Especially numbers. Before we use pickle we need a way to grab the current_directory the file we are working in is inside. For this we use pathlib.Path -
from pathlib import Path
current_directory = Path(__file__).parent
Excellent. For this tutorial I will be using a txt file. In order to get through directories I am going to use os -
from pathlib import Path
import os
current_directory = Path(__file__).parent
file = os.path.join(current_directory, 'DataFolder', 'Data.txt') #os.path.join joins together all the strings to return a path
Now it is time to use pickle. The two modules we are using from pickle are pickle.dump (save) and pickle.load (load). Here is pickle.save in actions -
from pathlib import Path
import os, pickle
current_directory = Path(__file__).parent #Get current directory
file = open(os.path.join(current_directory, 'DataFolder', 'Data.txt'), 'wb') #wb = write bytes because we are saving or writing
dataToSave = [1, 'foo', '2', 43]

pickle.dump(dataToSave, file) #We first give it the data to save, then the file to save it to
The pickle.load module works similarly. Here is how it works -
from pathlib import Path
import os, pickle
current_directory = Path(__file__).parent #Get current directory
file = open(os.path.join(current_directory, 'DataFolder', 'Data.txt'), 'rb') #rb = read bytes because we are reading the file

loadedData = pickle.load(file) #We give it the file and it loads in everything from the file. That data is the loaded as the variable loadedData

Hope there aren't any mistakes in there
Reply
#2
https://www.benfrederickson.com/dont-pickle-your-data/
Recommended Tutorials:
Reply
#3
And so that it's in this thread - JSON covers a huge fraction of serialization needs.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020