python进阶突破——关闭流要点
ztj100 2025-05-26 20:19 21 浏览 0 评论
在 Python 中正确关闭 I/O 流(文件、网络连接等)是避免资源泄漏的关键操作。以下是 关闭流的完整要点 和最佳实践:
二、关闭流的 4 种方法
1. 使用with语句(推荐)
- 自动关闭:离开 with 块时自动调用 close()
- 异常安全:即使发生异常也会关闭
with open('file.txt', 'r') as f: # 无需手动关闭
data = f.read()
# 此处文件已自动关闭
2. 手动调用close()
- 必须配合 try-finally 确保关闭
f = open('file.txt', 'r')
try:
data = f.read()
finally:
f.close() # 确保执行
3. 使用contextlib.closing(兼容非上下文对象)
- 适用于不支持 with 的旧式对象
from contextlib import closing
from urllib.request import urlopen
with closing(urlopen('http://example.com')) as webpage:
content = webpage.read()
# 连接自动关闭
4. 流对象的__del__方法(不推荐)
- 依赖垃圾回收机制关闭(不可靠!)
f = open('file.txt', 'r')
data = f.read()
# 不显式关闭,等待垃圾回收(可能延迟或失败)
三、需要关闭的常见流对象
流类型 | 关闭方法 | 典型场景 |
文件对象 | close() 或 with | 文件读写 |
网络连接(socket) | shutdown() + close() | TCP/UDP 通信 |
数据库连接 | connection.close() | SQLite/MySQL 操作 |
压缩文件流 | zipfile.close() | ZIP 文件解压 |
子进程管道 | subprocess.PIPE 的清理 | 进程间通信 |
四、关闭流的注意事项
1. 避免重复关闭
f = open('file.txt', 'r')
f.close()
f.close() # 抛出 ValueError: I/O operation on closed file
2. 检查流状态
f = open('file.txt', 'r')
print(f.closed) # False
f.close()
print(f.closed) # True
3. 处理嵌套流
# 多层 with 自动管理
with open('file1.txt', 'r') as f1, open('file2.txt', 'w') as f2:
f2.write(f1.read())
# 两个文件均自动关闭
4. 缓冲区的刷新(Flush)
- 关闭前会自动 flush,但显式调用更可靠:
with open('log.txt', 'a') as f:
f.write("重要日志")
f.flush() # 立即写入磁盘(如崩溃时保数据)
五、高级场景处理
1. 自定义支持with的类
class DatabaseConnection:
def __enter__(self):
self.conn = connect_to_db()
return self.conn
def __exit__(self, exc_type, exc_val, exc_tb):
self.conn.close()
with DatabaseConnection() as db:
db.execute("SELECT ...")
2. 异步流的关闭
async with aiofiles.open('file.txt', 'r') as f:
content = await f.read()
# 异步自动关闭
3. 标准输入输出的关闭(通常不需要)
import sys
sys.stdout.close() # 危险!会使后续 print 报错
六、资源泄漏检测工具
静态检查:
- Pylint 规则:W1514(未关闭的文件)
# pylint 会警告
f = open('file.txt', 'r')
data = f.read() # [W1514] 未关闭的文件
运行时检测:
- 使用 resource 模块监控文件描述符:
import resource
print(resource.getrlimit(resource.RLIMIT_NOFILE)) # 查看限制
七、总结:关闭流的最佳实践
- 首选 with 语句(安全简洁)
- 手动关闭时必须用 try-finally(防遗漏)
- 避免依赖垃圾回收(不可靠)
- 重要数据显式 flush()(防丢失)
- 定期检查资源泄漏(尤其长期运行的服务)
关键原则:
"谁打开,谁关闭;早关闭,早安心"
对每个 open() 或 connect(),必须有一个对应的关闭操作!
相关推荐
- 10条军规:电商API从数据泄露到高可用的全链路防护
-
电商API接口避坑指南:数据安全、版本兼容与成本控制的10个教训在电商行业数字化转型中,API接口已成为连接平台、商家、用户与第三方服务的核心枢纽。然而,从数据泄露到版本冲突,从成本超支到系统崩溃,A...
- Python 文件处理在实际项目中的困难与应对策略
-
在Python项目开发,文件处理是一项基础且关键的任务。然而,在实际项目中,Python文件处理往往会面临各种各样的困难和挑战,从文件格式兼容性、编码问题,到性能瓶颈、并发访问冲突等。本文将深入...
- The Future of Manufacturing with Custom CNC Parts
-
ThefutureofmanufacturingisincreasinglybeingshapedbytheintegrationofcustomCNC(ComputerNumericalContro...
- Innovative Solutions in Custom CNC Machining
-
Inrecentyears,thelandscapeofcustomCNCmachininghasevolvedrapidly,drivenbyincreasingdemandsforprecisio...
- C#.NET serilog 详解(c# repository)
-
简介Serilog是...
- Custom CNC Machining for Small Batch Production
-
Inmodernmanufacturing,producingsmallbatchesofcustomizedpartshasbecomeanincreasinglycommondemandacros...
- Custom CNC Machining for Customized Solutions
-
Thedemandforcustomizedsolutionsinmanufacturinghasgrownsignificantly,drivenbydiverseindustryneedsandt...
- Revolutionizing Manufacturing with Custom CNC Parts
-
Understandinghowmanufacturingisevolving,especiallythroughtheuseofcustomCNCparts,canseemcomplex.Thisa...
- Breaking Boundaries with Custom CNC Parts
-
BreakingboundarieswithcustomCNCpartsinvolvesexploringhowadvancedmanufacturingtechniquesaretransformi...
- Custom CNC Parts for Aerospace Industry
-
Intherealmofaerospacemanufacturing,precisionandreliabilityareparamount.Thecomponentsthatmakeupaircra...
- Cnc machining for custom parts and components
-
UnderstandingCNCmachiningforcustompartsandcomponentsinvolvesexploringitsprocesses,advantages,andcomm...
- 洞察宇宙(十八):深入理解C语言内存管理
-
分享乐趣,传播快乐,增长见识,留下美好。亲爱的您,这里是LearingYard学苑!今天小编为大家带来“深入理解C语言内存管理”...
- The Art of Crafting Custom CNC Parts
-
UnderstandingtheprocessofcreatingcustomCNCpartscanoftenbeconfusingforbeginnersandevensomeexperienced...
- Tailored Custom CNC Solutions for Automotive
-
Intheautomotiveindustry,precisionandefficiencyarecrucialforproducinghigh-qualityvehiclecomponents.Ta...
- 关于WEB服务器(.NET)一些经验累积(一)
-
以前做过技术支持,把一些遇到的问题累积保存起来,现在发出了。1.问题:未能加载文件或程序集“System.EnterpriseServices.Wrapper.dll”或它的某一个依赖项。拒绝访问。解...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- 10条军规:电商API从数据泄露到高可用的全链路防护
- Python 文件处理在实际项目中的困难与应对策略
- The Future of Manufacturing with Custom CNC Parts
- Innovative Solutions in Custom CNC Machining
- C#.NET serilog 详解(c# repository)
- Custom CNC Machining for Small Batch Production
- Custom CNC Machining for Customized Solutions
- Revolutionizing Manufacturing with Custom CNC Parts
- Breaking Boundaries with Custom CNC Parts
- Custom CNC Parts for Aerospace Industry
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)