try...except...finally
使用 with as 语句操作上下文管理器(context manager),它能够帮助我们自动分配并且释放资源
with 表达式 [as target]:
代码块# 1、打开文件
file = open("1.txt")
# 2、读取文件
data = file.read()
# 3、手动关闭文件
file.close() 在第二步假设文件读取的时候发生异常,没有做任何处理,就不会执行第三步,导致程序可能会泄露文件描述符
try:
# 打开文件、读取文件
f = open('xxx')
data = f.read()
except Exception as e:
# 捕获异常
pass
finally:
# 关闭文件
f.close()with open("1.txt") as file:
data = file.read()with open("input.txt") as in_file, open("output.txt", "w") as out_file:
# 从 input.txt 读取内容
# 转换内容
# 将转换后的内容写入output.txt
passwith open("input.txt") as in_file:
with open("output.txt", "w") as out_file:
passimport pathlib
file_path = pathlib.Path("a.txt")
with file_path.open("w") as file:
file.write("Hello, World!")无论何时加载外部文件的程序都应检查可能存在的问题,例如文件丢失、读写访问等
import pathlib
import logging
file_path = pathlib.Path("a.txt")
try:
with file_path.open("w") as file:
file.write("Hello, World!")
except OSError as error:
logging.error("Writing to file %s failed due to: %s", file_path, error)import os
with os.scandir(".") as entries:
for entry in entries:
print(entry.name, "->", entry.stat().st_size, "bytes")__init__.py -> 178 bytes
a.txt -> 13 bytes
1_上下文管理器.py -> 2168 bytes# 高精度计算
from decimal import Decimal, localcontext
with localcontext() as ctx:
ctx.prec = 42
res = Decimal("1") / Decimal("42")
print(res)0.0238095238095238095238095238095238095238095