python 文件輸入/輸出
可以使用file類打開一個文件,使用file的read、readline和write來恰當?shù)淖x寫文件。對文件讀寫能力取決于打開文件時使用的模式,常用模式、有讀模式("r")、寫模式("w")、追加模式("a"),文件操作之后需要調用close方法來關閉文件。
1 test = '''\
2 This is a program about file I/O.
3
4 Author: Peter Zhange
5 Date: 2011/12/25
6 '''
7
8 f = file("test.txt", "w") # open for writing, the file will be created if the file doesn't exist
9 f.write(test) # write text to file
10 f.close() # close the file
11
12 f = file("test.txt") # if no mode is specified, the default mode is readonly.
13
14 while True:
15 line = f.readline()
16 if len(line) == 0: # zero length indicates the EOF of the file
17 break
18 print line,
19
20 f.close()
點擊加載更多評論>>