每天开心一点

Python中as的三种用法

2020-09-23 12:04:00    六月    881    来源: https://blog.csdn.net/weixin_44306005/article/details/93975548

1.with...as...

第一种是和with结合使用,主要用于文件的读写操作,省去了关闭文件的麻烦。

写法:

with open("文件路径","读写方式") as 赋值变量:

    执行代码块

实例:

#test.py

with open("1.txt") as f:

    print f.read()

2.导入模块起别名

第二种是导入模块是对模块进行重命名,也就是给模块起一个别名。

3.except结合使用

第三种是和except组合使用,将捕获到的异常对象赋值给e。

第二种和第三种的实例代码:

#第二种,给traceback起别名为a

import traceback as a

try:

    while 1/0 < 0:

        print True

#第三种,将异常赋值给e

except Exception as e:

    print "e=",e

    a.print_exc()

参考: https://blog.csdn.net/weixin_44306005/article/details/93975548

https://www.jb51.net/article/65268.htm