# How to save/load a Model (Pickle) with a specific path/directory

I seems like a very basic think but I couldnt find an answer to it.

I want to save my model to a specific directory using pickle. The two algorithms below work fine for saving it in the same directory as the code itself but I want to save all my models in a dedicated folder. I tried to just change the "filename" to "filepath" and well, make it a path but the world isnt that easy it seems.

• Example Path: C:\Learning\Python\Data Science\02_TrainedModels

.

# save the model to disk
filename = 'Father_Son_Height_Model.pckl'
pickle.dump(lm, open(filename, 'wb'))

filename = 'Father_Son_Height_Model.pckl'


With This Code:

# save the model to disk
filepath = r'H:\99_Lernen\Python\Data Science\02_Trained Models\Father_Son_Height_Model.pckl'
pickle.dump(lm, open(filepath, 'wb'))


I get this Error: FileNotFoundError: [Errno 2] No such file or directory: 'H:\99_Lernen\Python\Data Science\02_Trained Models\Father_Son_Height_Model.pckl'

In this line of code:

pickle.dump(lm, open(filepath, 'wb'))

• What error do you get? – Dan Scally Sep 20 '19 at 7:52
• I edited it in. (a "x" appeard in the path) – G.M Sep 20 '19 at 8:00
• Probably needs to be a raw string literal. Try setting filepath = r'H:\99_Lernen\Python\Data Science\02_Trained Models\Father_Son_Height_Model.pckl'. Note the "r" preceding the opening quote. – Dan Scally Sep 20 '19 at 8:02
• Leads to a different error (see question). Intressting detail: In the Console the path is shown with two \\ instead of \ But when I copy it here it is shown with one \. Also the original variable text is with one \. Maybe just strange display from the Console but maybe helpfull. – G.M Sep 20 '19 at 8:10
• Nah that's ok. Regarding the new error...that path definitely does exist, right? – Dan Scally Sep 20 '19 at 8:12