0
$\begingroup$

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' 
loaded_model =    pickle.load(open(filename, 'rb'))

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'))
$\endgroup$
  • $\begingroup$ What error do you get? $\endgroup$ – Dan Scally Sep 20 '19 at 7:52
  • $\begingroup$ I edited it in. (a "x" appeard in the path) $\endgroup$ – G.M Sep 20 '19 at 8:00
  • $\begingroup$ 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. $\endgroup$ – Dan Scally Sep 20 '19 at 8:02
  • $\begingroup$ 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. $\endgroup$ – G.M Sep 20 '19 at 8:10
  • $\begingroup$ Nah that's ok. Regarding the new error...that path definitely does exist, right? $\endgroup$ – Dan Scally Sep 20 '19 at 8:12
2
$\begingroup$

The "\" escapes the following sign when parsed, so the path cannot be read.

Use "/" instead and it should work. Also this question was probably more of a SO question ;)

| improve this answer | |
$\endgroup$
  • $\begingroup$ Yeah probably true, came from a MS problem and thats kinda a follow up, but considering the solution i guess you are right. And Thx off course ^^ $\endgroup$ – G.M Sep 20 '19 at 8:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.