python Day9 else 和with

mac2024-11-08  47

Day9 else和with

python中else一共有三种用法: 1.if…else; (如果满足条件就。。。否则。。。)

for/while…else; (如果循环顺利执行,就执行else)

try…except…else;(如果try里面没有异常,就执行else)

2.python 中for/while …else 在循环体内没有break,return或者异常出现才执行else语句;try…except…else在try中无异常时执行else。

3.总结就是if里面有问题就执行else。for、while、try里面没有异常才执行else

python with主要是做善后工作,比如说文件处理,获取一个文件句柄后从文件中读取数据,然后关闭文件句柄。

没有with 的代码:

file=open(file_name) data=file.read() file.close()

但是可能出现两个问题:

1.忘记关闭文件句柄,那么写入的内容不会被记录。

2.文件打开了,但是读取异常。

下面是和加强版本:

try: file=open(file_name) except: print('fail to open') finally: file.close()

这样虽然解决了问题,但是代码不简洁。

下面是with版本:

with open(file_name) as file: data=file.read()

如果有多个项,我们可以这么写:

with open(file_name1) as file1,open(file_name2) as file2:
最新回复(0)