你可以通過(guò)創(chuàng)建一個(gè)file類的對(duì)象來(lái)打開(kāi)一個(gè)文件,分別使用file類的read、readline或write方法來(lái)
恰當(dāng)?shù)刈x寫(xiě)文件。對(duì)文件的讀寫(xiě)能力依賴于你在打開(kāi)文件時(shí)指定的模式。最后,當(dāng)你完成對(duì)文
件的操作的時(shí)候,你調(diào)用close方法來(lái)告訴Python我們完成了對(duì)文件的使用。
#!/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!
'''
= file('poem.txt''w'# open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
= 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!

它如何工作
首先,我們通過(guò)指明我們希望打開(kāi)的文件和模式來(lái)創(chuàng)建一個(gè)file類的實(shí)例。模式可以為讀模式
('r')、寫(xiě)模式('w')或追加模式('a')。事實(shí)上還有多得多的模式可以使用,你可以使用
help(file)來(lái)了解它們的詳情。
我們首先用寫(xiě)模式打開(kāi)文件,然后使用file類的write方法來(lái)寫(xiě)文件,最后我們用close關(guān)閉這個(gè)文
件。