位置:首頁 > 軟件操作教程 > 編程開發(fā) > Python > 問題詳情

python 文件輸入/輸出

提問人:楊紫紅發(fā)布時間:2020-11-20

可以使用file類打開一個文件,使用file的read、readline和write來恰當?shù)淖x寫文件。對文件讀寫能力取決于打開文件時使用的模式,常用模式、有讀模式("r")、寫模式("w")、追加模式("a"),文件操作之后需要調(diào)用close方法來關(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()

繼續(xù)查找其他問題的答案?

相關(guān)視頻回答
回復(0)
返回頂部