简体   繁体   中英

Pickle: file or directory not found

When i execute below code, I get the error

import pickle
import numpy as np
from random import gauss

path ='/flash/data/'
a = [gauss(1.5, 2) for i in range(1000)]
pkl_file = open(path +'data.pkl', 'w')

%time pickle.dump(a, pkl_file)

I get the following error (even though i created /flash/data/)

IOError Traceback (most recent call last)

<ipython-input-4-ac470dd231a6> in <module>()

      1 import pickle

----> 2 pkl_file = open (path + 'data.pkl','w')

      3 get_ipython().magic(u'time pickle.dump(a,pkl_file)')

IOError: [Errno 2] No such file or directory: '/flash/data/data.pkl'

It is a mistake on that book. The path should be: path ='./flash/data/'. A "." is missed.

The correction for python 3 should be as following,

import os
os.makedirs(path, exist_ok=True)     #create directory when non-existing
path = './flash/data/'               #do not miss the '.'
import numpy as np
from random import gauss
a = [gauss(1.5, 2) for i in range(1000000)]
import pickle
pkl_file =  open(path+'.data.pkl','wb')     #use 'wb' instead of 'w' to avoid TypeError

%time pickle.dump(a, pkl_file)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM