代码之家  ›  专栏  ›  技术社区  ›  helpermethod

Python with statement-是否还需要旧式文件处理?

  •  1
  • helpermethod  · 技术社区  · 14 年前

    拥有 with 语句,是否需要打开文件/检查异常/手动关闭资源,如

    try:
      f = open('myfile.txt')
    
      for line in f:
        print line
    except IOError:
      print 'Could not open/read file'
    finally:
      f.close()
    
    1 回复  |  直到 14 年前
        1
  •  5
  •   Tim Pietzcker    14 年前

    当前代码试图处理未找到文件或访问权限不足等异常,这些异常 with open(file) as f: 布洛克不会这么做的。

    finally: 布洛克会提出 NameError 自从 f 不会被定义的。

    with 块,出现的任何异常(无论是哪种类型,可能是代码中被零除的情况) 仍将被引发,但即使您不处理它,您的文件也将始终正确关闭。这是完全不同的。

    try:
        with open("myfile.txt") as f:
            do_Stuff()  # even if this raises an exception, f will be closed.
    except IOError:
        print "Couldn't open/read myfile.txt"