1、什么是文件
文件是操作系统提供给用户或者应用程序的一种操作硬盘的机制/功能
2、为何要用文件
应用程序---->用户
操作系统---->文件
计算机硬件-->硬盘
3、如何用文件
3.1、文件操作的基本流程:
1、应用程序打开文件,拿到一个文件对象/文件句柄
2、调用文件句柄下的读、写操作
3、关闭文件,回收操作系统资源
f = open('a.text',mode="r",encoding="utf-8")
f1 = f.read()
print(f1)
f.close()
3.2、上下文管理
用with会自动关闭文件
with open('aaa.text',mode='rt',encoding='utf-8')as f:
f.read()
3.3、文件的mode:
控制文件读写操作的模式:
r(默认):只读,文件不存在报错
w:只写,文件存在覆盖,重写
a:只写,追加写
控制文件读写内容的模式:
t(默认):无论读写都是以字符串为单位,必须指定encoding参数。---->只能用在文本文件
b:无论读写都是二进制(byte)单位,一定不能指定encoding参数---->可以用在任何文件
3.3.1、rt:只读模式,文件不存在报错,文件存在,文件指针在开头
with open('a.text',mode='rt',encoding='utf-8') as f:
print(f.read())
3.3.2、wt:只写模式,文件不存在则创建新文档,文件指针处于文件开头,文件存在则清空
with open('a.text',mode='wt',encoding='utf-8') as f:
f.write("你好啊\n")
f.write("哈哈哈\n")
3.3.3、at:只追加写模式,文件不存在则创建空文档,文件指针处于文件末尾,文件存在则指针处于文件末尾
with open('a.text',mode='at',encoding='utf-8') as f:
f.write('呜呼\n')
f.write('哀哉\n')
3.3.4、b模式:
with open('a.text',mode="rb")as f:
f1 = f.read().decode('utf-8')
print(f1)
with open('a.text',mode='wb') as f:
f.write('第一句话:\n'.encode('utf-8'))
with open('a.text',mode='ab') as f:
f.write('第二句话。\n'.encode('utf-8'))
f.write('第三句话。\n'.encode('utf-8'))
f.write('第四句话。\n'.encode('utf-8'))
拷贝文件实例:
with open('a.text',mode='rb') as a,open('b.text',mode="wb") as b:
for line in a:
b.write(line)
3.3.5、+模式
'+':表示可以同时读写某些文件
r+:读写(可读可写)
w+:写读(可读可写)
a+:写读(可读可写)