Python,how do you work(二)
1697 ワード
pythonについて、私は前の編でいくつかの良い例とpythonの中でどのようにclassの方法とclassの内部の方法を作成して、構造の方法、分析の方法などを話しました
次にpythonによるIOの操作について説明します
実はpythonのファイル操作はc言語に似ています.正直に言って.cよりずっと便利だと思います.
例を挙げてすべてを説明する.
fileクラスのread,readlineまたはwirteメソッドを使用して読み書き操作を実行
簡単な感じでしょう.
pythonにはメモリもあります
cPickleはストレージです
以下に例を示します.
次にpythonによるIOの操作について説明します
実はpythonのファイル操作はc言語に似ています.正直に言って.cよりずっと便利だと思います.
例を挙げてすべてを説明する.
fileクラスのread,readlineまたはwirteメソッドを使用して読み書き操作を実行
poem = '''\
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
簡単な感じでしょう.
pythonにはメモリもあります
cPickleはストレージです
以下に例を示します.
import 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 storage
f = file(shoplistfile)
storedlist = p.d(f)
print storedlist