文件操作

使用with方式处理文件文件关闭

with open(r'somefileName') as somefile:
    for line in somefile:
        print line
        # ...more code

使用try...finally处理文件关闭

somefile = open(r'somefileName')
try:
    for line in somefile:
        print line
        # ...more code
finally:
    somefile.close()

数据库操作

from django.db import connections

使用with方式

with connection.cursor() as c:
    c.execute(...)

使用try...finally方式

c = connection.cursor()
try:
    c.execute(...)
finally:
    c.close()

参考资料:https://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/

[ 编辑 | 历史 ]
最近由“jilili”在“2017-04-22 11:46:18”修改