这个例子展示了尝试打开一个文件,然后把内容打印到屏幕上:
print(line, end="")
以上这段代码的问题是,当执行完毕后,文件会保持打开状态,并没有被关闭。
关键词 with 语句就可以保证诸如文件之类的对象在使用完之后一定会正确的执行他的清理方法:
for line in f:
print(line, end="")
以上这段代码执行完毕后,就算在处理过程中出问题了,文件 f 总是会关闭。
更多 with 关键字内容参考:Python with 关键字
相关内容
Python assert(断言)
Python with 关键字










哇咔咔
hao***nyang249@163.com
在 python3 中,处理带有参数的异常的方法如下:
# 定义函数def temp_convert(var): try: return int(var) except (ValueError) as Argument: print ("参数没有包含数字 ", Argument)# 调用函数temp_convert("xyz");哇咔咔
hao***nyang249@163.com
Yota Togashi
116***47@qq.com
异常是可以向后推移的,所以我们一般看到的报错的位置是相对靠后的,下例:
def test1(): print('test1-1') print(num) print('test2-2')def test2(): print('test2-1') test1() print('test2-2')def test3(): try: print('test3-1') test1() print('test3-2') except Exception as result: print('检测出异常{}'.format(result)) print('test3-2')test3()print('-------------')test2()Yota Togashi
116***47@qq.com
黑桃六
pan***a68@hotmail.com
with 是个好东西,打开文件的时候多使用它,可以避免很多问题。例如:
temp = os.open('test_text.txt', os.O_RDWR | os.O_CREAT)temp_file = os.fdopen(temp, 'r')print(str(temp_file.read()))os.close(temp)就可以简化成:
with open('test_text.txt', 'r') as f: print(f.read())黑桃六
pan***a68@hotmail.com
redhands
zho***cc@qq.com
参考地址
Python3 内置异常类型的结构:
redhands
zho***cc@qq.com
参考地址
CJimer
604***021@qq.com
使用一个快捕捉多个异常:
def model_exception(x,y): try: b = name a =x/y except(ZeroDivisionError,NameError,TypeError): print('one of ZeroDivisionError or NameError or TypeError happend')#调用函数结果model_exception(2,0)输出如下:
CJimer
604***021@qq.com
小c
413***465@qq.com
参考地址
捕获所有异常:
try: ...except Exception as e: ... log('Reason:', e) # Important!这个将会捕获除了 SystemExit 、 KeyboardInterrupt 和 GeneratorExit 之外的所有异常。 如果你还想捕获这三个异常,将 Exception 改成 BaseException 即可。