Python 基础
(Chrome无法播放优酷? 网址框输入"chrome://settings/content/", 勾选允许 Flash Player. 实在不行? 请 点击这里)
读写文件 2
作者: Huanyu Mao 编辑: 莫烦 2016-11-03
给文件增加内容
我们先保存一个已经有3行文字的 “my file.txt” 文件, 文件的内容如下:
This is my first test.
This is the second line.
This the third
然后使用添加文字的方式给这个文件添加一行 “This is appended file.”, 并将这行文字储存在 append_file 里,注意\n的适用性:
append_text='\nThis is appended file.' # 为这行文字提前空行 "\n"
my_file=open('my file.txt','a') # 'a'=append 以增加内容的形式打开
my_file.write(append_text)
my_file.close()
""""
This is my first test.
This is the second line.
This the third line.
This is appended file.
""""
#运行后再去打开文件,会发现会增加一行代码中定义的字符串
总结
- 掌握 append 的用法 :
open('my file.txt','a')打开类型为a,a即表示 append - 可以思考,如果用
w形式打开,运行后会发生什么呢?
莫烦Python