全部博文(64)
分类: Python/Ruby
2009-09-22 10:21:26
#!/usr/bin/python
# Filename: using_file.pypoem =
'''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''f =
file
(
'poem.txt'
,
'w'
)
# open for 'w'riting
f.write(poem)
# write text to file
f.close()
# close the file
f =
file
(
'poem.txt'
)
# if no mode is specified, 'r'ead mode is assumed by default
while
True
:
line = f.readline() if
len
(line) ==
0
:
# Zero length indicates EOF
break
print
line,
# Notice comma to avoid automatic newline added by Python
f.close()
# close the file
#!/usr/bin/python
# Filename: pickling.pyimport
cPickle
as p
#import pickle as p
shoplistfile =
'shoplist.data'
# the name of the file where we will store the object
shoplist = [
'apple'
,
'mango'
,
'carrot'
]
# Write to the file
f =
file
(shoplistfile,
'w'
)
p.dump(shoplist, f) # dump the object to a file
f.close()
del
shoplist
# remove the shoplist
# Read back from the storagef =
file
(shoplistfile)
storedlist = p.load(f)print
storedlist