Save the file and rename the old version

I have pickled (dumped) my model and saved it for use in a web application. Each time I re-run analysis of the model, the file is pickled again and saved in the same folder under the (file name + date). In case the new file is created on the same day as the last version I would like to rename the old version.

I attempted to rename the old file by adding '_archived'
to the end. The code below correctly creates a new file when none exists but when file already exists re-running it removes old file and throws error.

path = r'C:scoring_model'
dest = os.path.join(path, 'test12')

now = pd.datetime.now()
date_now = str(now.date())
model_name = 'model' + '_' + date_now
model_loc = os.path.join(dest, model_name)

if os.path.exists(model_loc):
    try:
        os.rename(model_loc, model_name + '_archived')

    except:
        os.remove(model_loc)
        os.rename(model_loc, model_name + '_archived')
        with open(model_loc, 'wb') as pfile:
            pickle.dump(scoring_model, pfile)

else:
    with open(model_loc, 'wb') as pfile:
        pickle.dump(scoring_model, pfile)

I get the following error:

WindowsError                              Traceback (most recent call last)
 in ()
     16     except:
     17         os.remove(model_loc)
---> 18         os.rename(model_loc, model_name + '_archived')
     19         with open(model_loc, 'wb') as pfile:
     20             pickle.dump(scoring_model, pfile)

WindowsError: [Error 2] The system cannot find the given file
Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Save the file and rename the old version

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录