【Python】通过Python来管理文件,进行读取、写入、追加等操作。open、write、read、close函数的写法

open() 函数常用形式是接收两个参数:文件名(file)和模式(mode)。

# _*_ coding: utf-8 _*_
# mode = w,当存在此文件,覆盖读写。不存在则新建。
f = open("d:/testfile.txt","w")
f.write("-->this a testfile...\n")
f.close()

# 打印内容。mode为空时,默认只读
f = open("d:/testfile.txt")
content01 = f.read()
print (content01)

# mode = a,当存在此文件,追加读写。不存在则新建。
f = open("d:/testfile.txt","a")
f.write("-->this a new testfile...\n")
f.close()

# 打印内容
f = open("d:/testfile.txt")
content02 = f.read()
print (content02)

运行结果:

-->this a testfile...

-->this a testfile...
-->this a new testfile...
发布了94 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/woshiyigerenlaide/article/details/104156968
今日推荐