一。内置函数
以下是python的内置函数:
二。
open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
“r”打开读取(默认)
“w”打开进行写入,首先截断文件
“x”创建一个新文件并打开它进行写入
“a”打开进行写入,如果文件存在,则追加到文件末尾
“b”二进制模式
“t”文本模式(默认)
“+”打开磁盘文件进行更新(读写)
“U”通用换行模式(已弃用)
1.读取文件 read():
# 打开文件
file = open("test_1.txt", encoding='utf-8')
# 读取数据
data = file.read()
print(data)
# 关闭文件
file.close()
2.常用模式
mode = 'a', 追加模式
mode = 'x', 原创模式,独创模式
mode = 'b', 二进制模式, 't'文本
注意:
1)在 w 模式下,如果之前没有这个文件,将会创建新文件
2)写入中文需要指定编码格式为 utf-8, GBK,否则会出现乱码。
例子1(追加:at):
file = open('test_1.txt', mode='at', encoding='utf-8')
# 写入数据
file.write("我是学渣")
# 关闭文件
file.close()
例子2(文件默认位置:r+)
file = open('test_1.txt', mode='r+', encoding='utf-8')
# 写入数据
file.write('新内容')
print(file.read())
# 关闭文件
file.close()
标签:文件,内置,python,写入,模式,mode,file,open
来源: https://www.cnblogs.com/newsss/p/12857477.html