Python-上下文管理
0 前言
1 open 语句
文件平时放在电脑的硬盘中,而CPU只能读写内存中的数据。所以电脑处理文件需要分为3步:
- 将硬盘中的文件复制进内存,并设置文件指针,对应
__enter__
方法 - 移动指针,将内存中文件数据转为字符串,或将字符串传入文件数据
- 使用完毕后清除内存中文件数据,对应
__exit__
方法。如果允许写入,则同时修改硬盘数据
注意项:
- 硬盘中的文件数据只能复制到内存中,或者被内存中数据覆盖,不能修改
- 内存中的文件数据是
_io.TextIOWrapper
格式,只能使用文件指针进行操作,对应read()
和write()
方法 read()
可以将内存中文件数据转换成字符串赋值给变量
f = open('/tmp/simple.txt', 'r', encoding='utf-8', errors='ignore') # f是_io.TextIOWrapper格式
data = f.read() # 将_io.TextIOWrapper格式转为字符串赋值给data
f.close() # 清除_io.TextIOWrapper格式数据,释放内存
Python内置函数open()
用于打开文件或创建文件对象
f = open(file_name, mode=, encoding=, errors=)
file_name
:文件名或文件地址mode
:指定文件的打开模式
encoding
:编码格式,通常'utf-8'
f
:文件指针,有以下方法
f.read()
:以字符串形式读取所有内容,文件指针会随着读取移动f.readlines()
:按行读取所有内容,返回列表,文件指针会随着读取移动f.close()
:关闭文件f.write(str)
:在文件指针处写入字符串
2 with open语句
open()
语句之后一定要有close()
,否则内存会一直被占用。Python提供了上下文管理器with
,程序在退出with
语句块时自动调用close()
。
即使with
语句中发生错误导致程序中断,程序依然会调用close()
保护内存。
with open('/tmp/simple.txt', 'r', encoding='utf-8', errors='ignore') as f:
data = f.read()
2.1 数据有效范围
with open('textsimple.txt', 'w+', encoding='utf-8', errors='ignore') as f:
f.write('[新建text内容]')
with open('textsimple.txt', 'r', encoding='utf-8', errors='ignore') as f:
data1 = f.read() # data1在with语句外有效,f在with语句外无效
with open('textsimple.txt', 'r', encoding='utf-8', errors='ignore') as f:
data2 = f.read() # 在with语句外已经无法再读取,data2错误
2.2 文件指针位置
read()
和write()
的同时会移动指针
with open('textsimple.txt', 'w+', encoding='utf-8', errors='ignore') as f:
f.write('[新建text内容,内容需要写的比较长]')
with open('textsimple.txt', 'r', encoding='utf-8', errors='ignore') as f:
data1 = f.read()
data2 = f.read()
print(data1) # data1能读出数据
print(data2) # data2时指针已在末尾,数据为空
r+
方式从头写入,覆盖原数据,会导致乱码
with open('textsimple.txt', 'w+', encoding='utf-8', errors='ignore') as f:
f.write('[新建text内容,内容需要写的比较长]')
with open('textsimple.txt', 'r+', encoding='utf-8', errors='ignore') as f:
f.write('[r+]方式写入的内容')
3) w+
方式会先清空原数据
with open('textsimple.txt', 'w+', encoding='utf-8', errors='ignore') as f:
f.write('[新建text内容,内容需要写的比较长]')
with open('textsimple.txt', 'w+', encoding='utf-8', errors='ignore') as f:
f.write('[w+]方式写入的内容')
4) a+
方式在原数据后面补充
with open('textsimple.txt', 'w+', encoding='utf-8', errors='ignore') as f:
f.write('[新建text内容,内容需要写的比较长]')
with open('textsimple.txt', 'a+', encoding='utf-8', errors='ignore') as f:
f.write('[a+]方式写入的内容')