else-with

mac2024-07-31  70

一,else 作用: 1,if-else 2,与while,for循环连用 3,与try-except连用

二,with 作用:减少代码量

未使用with语句

# -*- coding: utf-8 -*- try: file=open('E:\\文档\\testfile\\testfile.txt') except: print('fail to open') finally: file.close()

使用with语句

# -*- coding: utf-8 -*- with open('E\\文档\\testfile\\testfile.text') as file: data=file.read()

可以看出来代码明显变得简洁,代码量大大减少 如果有多个项,我们可以这么写:

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