使用 write 函数向已有文件写入数据 , 会清空该文件中的数据 , 代码展示如下 :
file1.txt 文件内容是 Hello World !
, 现在以只写模式打开文件 , 并且向 file1.txt 中写入文件 ;
代码实例 :
"""
文件操作 代码示例
"""
import time
with open("file1.txt", "w", encoding="UTF-8") as file:
print("使用 write / flush 函数向文件中写出数据(以只读方式打开文件): ")
# 写出数据
file.write("Tom and Jerry")
# 刷新数据
file.flush()
# 关闭文件
file.close()
执行结果 : 执行上述代码后 , file1.txt 变为 Tom and Jerry
, 之前文件中的内容被清空 ;
追加模式是 a
模式 , 使用 open 函数 追加模式 打开文件 :
使用 追加模式 打开文件代码 :
open("file1.txt", "a", encoding="UTF-8")
上述代码的作用是 : 打开 file1.txt 文件 , 以追加模式 a
打开 , 文件的编码为 UTF-8 ;
代码示例 :
"""
文件操作 代码示例
"""
import time
with open("file1.txt", "a", encoding="UTF-8") as file:
print("使用 write / flush 函数向文件中写出数据(以追加模式打开文件): ")
# 写出数据
file.write("Tom and Jerry")
# 刷新数据
file.flush()
# 关闭文件
file.close()
执行结果 : 执行后 , 文件在 Hello World!
文本的基础上 , 在后面追加了 Tom and Jerry
数据 , 最终得到文件中的数据为 Hello World!Tom and Jerry
;
在 open 函数中 , 使用追加模式 a
打开一个不存在的文件 , 此时会创建该文件 , 并向其中写入数据 ;
代码实例 :
"""
文件操作 代码示例
"""
import time
with open("file2.txt", "a", encoding="UTF-8") as file:
print("使用 write / flush 函数向文件中写出数据(以追加模式打开文件): ")
# 写出数据
file.write("Tom and Jerry")
# 刷新数据
file.flush()
# 关闭文件
file.close()
执行结果 : 打开 file2.txt 文件 , 此时没有该文件 , 会创建 一个新的 file2.txt 文件 , 写入内容之后文件内容为 Tom and Jerry
, 这是新写入的数据 ;
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有