open和file方法类似
打开文件使用后,要确保关闭,才是安全的:
#open your file here
try:
#write data to your file
finally:
file.close()
try:
f=open('test.txt','r')
except:
pass
else:
babababbaba
finally:
f.close()
相比之下,with语句简洁许多,而且自带关闭
with open("somefile.txt") as somefile:
do_something(somefile)
with open('abc.txt','r') as f:
print 'babababa'