Reputation: 3558
try.py:
import pickle
f=open('abc.dat','w')
x=[320,315,316]
y=pickle.load(f)
f.close()
f=open('abc.dat','w')
for i in x:
y.append(i)
pickle.dump(y,f)
f.close()
use.py
import pickle
import os
os.system('try.py')
f=open('abc.dat', 'r')
print "abc.dat = "
x=pickle.load(f)
print x
print "end of abc.dat"
f.close();
y=x[:]
for z in x:
y.remove(z)
print "removing " + str(z)
print str(y) + " and " + str(x)
f=open('abc.dat', 'w')
pickle.dump(y, f)
f.close()
error:
Traceback (most recent call last):
File "G:\parin\new start\use.py", line 7, in <module>
x=pickle.load(f)
File "C:\Python26\lib\pickle.py", line 1370, in load
return Unpickler(file).load()
File "C:\Python26\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Python26\lib\pickle.py", line 880, in load_eof
raise EOFError
EOFError
Upvotes: 1
Views: 850
Reputation: 29655
Example doesn't work for me. try.py
fails when the file doesn't exist.
My big recommendation, though, is to look at using JSON instead of pickle, as you'll have more cross-platform flexibility and the interface is more flexible.
For example, use this to create a file of JSON lines:
import json,random
with open("data.txt","w") as f:
for i in range(0,10):
info = {"line":i,
"random":random.random()}
f.write(json.dumps(info)+"\n")
(Make info
whatever you want, obviously.)
Then use this to read them:
import json
for line in open("data.txt"):
data = json.loads(line)
print("data:" + str(data))
Upvotes: 1
Reputation: 287885
The error is in try.py
:
f=open('abc.dat','w')
y=pickle.load(f)
Note that the 'w'
mode resets the file to size 0 (i.e. deletes its content). Pass 'r'
or nothing at all to open abc.dat
for reading.
Upvotes: 3