最近在学一门机器学习的公开课,作业推荐使用python2.6或2.7,但因为电脑上已经装了python3,懒得换就没有改。运行示例程序时,发现pickle模块老是报错:TypeError: a bytes-like object is required, not ‘str’.
对应的代码如下:
authors_file_handler = open(authors_file, "r")
authors = pickle.load(authors_file_handler)
在网上找了一圈没有找到合理的解决方法,后来发现,只要把读写模式改成“wb”或“rb”即可。代码如下:
authors_file_handler = open(authors_file, "rb")
authors = pickle.load(authors_file_handler)
这样就可以顺利运行了。
题外话,python3以上的版本中,Pickle和cPickle统一为了模块Pickle,所以如果在python2中看到关于cPickle的代码,直接把它改成Pickle即可。