python with (as)语句
with语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的“清理”操作,释放资源,比如文件使用后自动关闭、线程中锁的自动获取和释放等。
例1:
url = ‘http://www.weather.com.cn/‘ + province + ‘/index.shtml‘
with urlopen(url) as fp:
contents = fp.read().decode()
例2:
with open("aaa.txt","r") as f: line = f.readline() # 调用文件的 readline()方法 av="" while line: if len(line.strip())>0: if line.strip()[0].isdigit(): a1=line bz=1 if line.strip()[0].isalpha(): a2=line bz=2 if line.find(tmp_value)>-1: if bz==2: av=av+a1+a2 if bz==1: line = f.readline() av=av+a1+line #print(line) line=f.readline() continue if len(av)!=0: print(av)
相关推荐
dflyzx 2020-09-17
higheels 2020-07-20
Ericbig 2020-07-19
yinyang00 2020-05-15
lijiuchangxin 2020-05-14
yogoma 2020-05-09
jacktangj 2020-04-19
Yyqingmofeige 2020-03-26
idning 2020-02-14
luenxin 2020-01-22
水痕 2020-01-18
chouliqingke 2020-01-08
secondid 2019-12-18
XCodeRush 2019-12-17
ryuhfxz 2019-11-20
qonsnow 2014-03-07
coulder 2019-11-17
wangxiaohua 2015-05-09