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
:
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
:
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