python-基础入门-3(对文件操作)

打开文件用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(
)
 7 txt.write(line2)
 8 txt.write(
)
 9 txt.write(line3)
10 txt.close()

分别将三行写入文件后再关闭。

原文地址:https://www.cnblogs.com/hongren/p/7143579.html