python-4-之with和open对比

来源:互联网 发布:淘宝定时上架怎么抢 编辑:程序博客网 时间:2024/05/29 18:48

open和file方法类似

打开文件使用后,要确保关闭,才是安全的:


#open your file heretry:    #write data to your filefinally:    file.close()

try:    f=open('test.txt','r')except:    passelse:    babababbabafinally:    f.close()


相比之下,with语句简洁许多,而且自带关闭

with open("somefile.txt") as somefile:do_something(somefile)

with open('abc.txt','r') as f:   print 'babababa'



原创粉丝点击