python 文件輸入/輸出
可以使用file類(lèi)打開(kāi)一個(gè)文件,使用file的read、readline和write來(lái)恰當(dāng)?shù)淖x寫(xiě)文件。對(duì)文件讀寫(xiě)能力取決于打開(kāi)文件時(shí)使用的模式,常用模式、有讀模式("r")、寫(xiě)模式("w")、追加模式("a"),文件操作之后需要調(diào)用close方法來(lái)關(guān)閉文件。
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()
點(diǎn)擊加載更多評(píng)論>>