1. 程式人生 > >python-基礎入門-3(對文件操作)

python-基礎入門-3(對文件操作)

col 文件打開 hello cnblogs you write line div 打印

打開文件用open()函數

open(filename)默認為讀取模式

等價於open(filename,‘r‘)

1 txt=open(filename)

2 print txt.read()

3 txt.close()

以上三行分別是將文件打開,將內容打印出來,將文件關閉。

文件寫入用‘w‘

 1 line1="hello"
 2 line2="how are you "
 3 line3="bye"
 4 txt=open(filename,w)
 5 txt.write(line1)
 6 txt.write(\n)
 7 txt.write(line2)
 8 txt.write(\n)
9 txt.write(line3) 10 txt.close()

分別將三行寫入文件後再關閉。

python-基礎入門-3(對文件操作)