读写文件 2

mac2024-05-21  35

给文件增加内容 

我们先保存一个已经有四行文字的 “test.txt” 文件, 文件的内容如下:

Python 2.7.16 |Anaconda, Inc. first line Second line Third line

然后使用添加文字的方式给这个文件添加一行 “appended content”, 并将这行文字储存在 test.txt 里,注意\n的适用性:

>>> append_text = '\nappended content' >>> my_file = open('test.txt','a') >>> my_file.write(append_text) >>> my_file.close() >>>

如果用 w 形式打开,则 将原来内容覆盖

总结 

掌握 append 的用法 :open('my file.txt','a') 打开类型为 a ,a 即表示 append
最新回复(0)