#!/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
(源文件:code/using_file.py)
輸出
$ python using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
它如何工作
首先,我們通過指明我們希望打開的文件和模式來創(chuàng)建一個 file 類的實例。模式可以為讀模式('r')、寫模式('w')或追加模式('a')。事實上還有多得多的模式可以使用,你可以使用 help(file)來了解它們的詳情。
我們首先用寫模式打開文件,然后使用 file 類的 write 方法來寫文件,最后我們用 close 關(guān)閉這個文件。
接下來,我們再一次打開同一個文件來讀文件。如果我們沒有指定模式,讀模式會作為默認的模式。在一個循環(huán)中,我們使用 readline 方法讀文件的每一行。這個方法返回包括行末換行符的一個完整行。所以,當一個 空的 字符串被返回的時候,即表示文件末已經(jīng)到達了,于是我們停止循環(huán)。
注意,因為從文件讀到的內(nèi)容已經(jīng)以換行符結(jié)尾,所以我們在 print 語句上使用逗號來消除自動換行。最后,我們用 close 關(guān)閉這個文件。
現(xiàn)在,來看一下 poem.txt 文件的內(nèi)容來驗證程序確實工作正常了