天天看點

Python讀書筆記第十一章:輸入/輸出

1.檔案

程式與使用者互動時,可以使用raw_input和print語句來完成這些功能。rjust可以得到一個按一定寬度右對齊的字元串。

通過建立一個file類的對象來打開一個檔案,分别使用read、readline或write方法來讀寫檔案。對檔案的讀寫能力依賴于你在打開檔案時指定的模式,最後通過調用close方法來告訴Python完成對檔案的使用。

#!/usr/bin/python
# Filename: using_file.py

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 using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
        use Python!           

模式可以為‘r’(read), 'w'(write), 'a'(append),此外還有很多的模式可以使用。

程式首先用w模式打開檔案,然後使用write方法來寫檔案,最後使用close關閉這個檔案。

如果沒有指定模式,讀模式會作為預設模式。在一個循環中,使用readline方法來讀每一行。這個方法傳回包括行末換行符的一個完整行。因為從檔案讀到的内容已經以換行符結尾,是以我們在print語句上使用都好來消除自動換行。

2.存儲器

Python的pickle子產品可以讓你在一個檔案中儲存任何Python對象,之後你又可以完整無缺地取出來。這被成為持久地儲存對象。與Pickle相同的還有一個cPickle子產品(用C語言編寫,速度快1000倍)。

#!/usr/bin/python
# Filename: pickling.py

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.load(f)
print storedlist           

輸出:

$ python pickling.py
['apple', 'mango', 'carrot']           

使用import...as文法以便于我們可以使用更短的子產品名稱。為了在檔案裡儲存一個對象,調用儲存器子產品的dump函數,把對象儲存到打開的檔案中。這個過程稱為儲存。然後使用load函數傳回來取會對象,這個過程稱為取儲存。