由于处理文件时try/except/finally模式相当常用,所以Python提供了一个语句对相关细节进行了抽象,对文件使用with语句时,可以大大减少代码量,因为有了with语句就不再需要包含一个finally组来处理文件的关闭,with自动帮你处理。来看下面的例子:
try:
data = open('this.txt', "w")
print("It's ...", file=data)
except IOError as err:
print('File Error: ' + str(err))
finnally:
if 'data' in locals():
data.close()
使用with就不需要finally了:
try:
with open('this.txt', "w") as data:
print("It's ...", file=data)
except IOError as err:
print('File Error: ' + str(err))
使用with时,不再需要操心关闭打开的文件,Python解释器自动帮你考虑这一点。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/25791987/viewspace-746258/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/25791987/viewspace-746258/