你可以通過創(chuàng)建一個file類的對象來打開一個文件,分別使用file類的read、readline或write方法來
恰當?shù)刈x寫文件。對文件的讀寫能力依賴于你在打開文件時指定的模式。最后,當你完成對文
件的操作的時候,你調(diào)用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!
'''
= 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!

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