How to 'pickle' an object to a certain directory?

with open('/full/path/to/file', 'wb') as f:
    pickle.dump(object, f)

If you wish to save the file to a sub-folder located inside the folder containing your code you can use the pathlib module. This will allow the code to work even if its location is moved on your computer, or you code is added to a different machine.

import the module:

from pathlib import Path

Set root equal to your current folder:

root = Path(".")

Create a path to your sub-folder and file name:

my_path = root / "my_sub_folder" / "my_file_name"

Open your file, dump data to your file, close your file:

my_file = open(my_path, 'wb')
my_file = pickle.dump("data_to_save", my_file)
my_file.close()
  • Note if your my_file doesn't currently exist you will want to create it before running this code. *

How about combination of pathlib and with, I think it more flexible and safer.

# from python 3.4
from pathlib import Path
my_path = Path("{path to you want to set root like . or ~}") / "path" / "to" / "file"
with my_path.open('wb') as fp:
    pickle.dump(object, fp)

You can just try

import pickle
filepath = r'<FolderName>/<FileName>.pkl'
pickle.dump(<model>, open(filepath, 'wb'))

so final code look likes If your Folder name is Models and you wanted to pickle randomForest Model

import pickle
filepath = r'Models/rfPickle.pkl'
pickle.dump(randomForest, open(filepath, 'wb'))