Python基础---Task09:else与with语句

mac2024-11-12  8

Python基础---Task09:else与with语句

elseif...else...分支语句try...except...else... with忽略文件名编码让对象支持上下文管理协议(with语句)创建临时文件

else

if…else…分支语句

if min > max: raise ValueError("min must be <= max") if a.shape[0] != out.shape[0]: raise ValueError("input and output arrays must be the same size") for i in range(a.shape[0]): if a[i] < min: out[i] = min elif a[i] > max: out[i] = max else: out[i] = a[i]

try…except…else…

with

忽略文件名编码

with open('xf1o.txt', 'w') as f: # Unicode编码文件名 f.write('Spicy!')

让对象支持上下文管理协议(with语句)

详细见Python3cookbook: https://python3-cookbook.readthedocs.io/zh_CN/latest/c08/p03_make_objects_support_context_management_protocol.html

创建临时文件

from tempfile import TemporaryFile # 引入模块 with TemporaryFile('w+t',encoding='utf-8') as f: # 文本模式使用 w+t ,utf-8编码 # Read/write to the file f.write('Hello World\n') f.write('Testing\n') f.seek(0) data = f.read()

12 days

参考文献: https://python3-cookbook.readthedocs.io/zh_CN/latest/index.html https://www.liaoxuefeng.com/wiki/1016959663602400

最新回复(0)