python 文件输入/输出
可以使用file类打开一个文件,使用file的read、readline和write来恰当的读写文件。对文件读写能力取决于打开文件时使用的模式,常用模式、有读模式("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()
点击加载更多评论>>