In [4]:
"""
An example to store the output without "pickle"
"""
testfile = 'nopickle.txt'
var1 = 1143
var2 = ["AECS", "LAYOUT", "KUNDALAHALLI"]
var3 = 58.30
var4 = ("Bangalore", 560037)
def ezhudhu():
with open(testfile, 'w+') as f:
f.write(str(var1))
f.write(str(var2))
f.write(str(var3))
f.write(str(var4))
f.close()
return None
def main():
ezhudhu()
if __name__ == '__main__':
main()
In [6]:
"""
Let us now read the contents of 'nopickle.txt', also check it's type
Does it retain the original type of the variables ?
"""
with open(testfile, 'r') as f:
print f.readline()
print(type(f.readline()))
In [7]:
"""
An example of store the outputin a file using 'pickle'
"""
import pickle
testfile = 'pickle.txt'
var1 = 1143
var2 = ["AECS", "LAYOUT", "KUNDALAHALLI"]
var3 = 58.30
var4 = ("Bangalore", 560037)
def baree():
with open(testfile, 'w+') as f:
pickle.dump(var1, f)
pickle.dump(var2, f)
pickle.dump(var3, f)
pickle.dump(var4, f)
f.close()
return None
def main():
baree()
if __name__ == '__main__':
main()
In [32]:
"""
Let us now read the contents of 'pickle.txt'.
Do the variables retain their types?
"""
def pickout(fileobj):
print "what's this file object : "
print fileobj
print "it's type : "
print type(fileobj)
print "==" * 5 + "==" * 5
while True:
pickline = pickle.load(fileobj)
yield pickline
with open('pickle.txt', 'rb') as f:
for info in pickout(f):
print info,
print type(info)
[Stackoverflow thread on reading file contents (written using pickle) in a loop] (http://stackoverflow.com/questions/18675863/load-data-from-python-pickle-file-in-a-loop)
In [33]:
"""
Example on how to read contents of 'pickle.txt'.
End of file condition handled.
"""
def pickout(fileobj):
print "what's this file object : "
print fileobj
print "it's type : "
print type(fileobj)
print "==" * 5 + "==" * 5
try:
while True:
pickline = pickle.load(fileobj)
yield pickline
except EOFError:
pass
with open('pickle.txt', 'rb') as f:
for info in pickout(f):
print info,
print type(info)
In [ ]: