文件句柄分配

File-handle assignment

考虑这样一种情况,您使用 with 语句打开文件并将其命名为 file_handle。然后从 with 块中打开一个新文件并将其分配给之前的 file_handle 如下:

with open('some/file') as file_handle:
    # some codes
    file_handle = open('another/file')
    # more codes

我的问题:在这种情况下会发生什么?事实上,我想知道以下问题的答案:

  1. 第一个 file_handle 会怎样?它会在分配后关闭还是保持打开状态?
  2. 如果赋值后with块发生异常,新打开的文件会不会关闭?
  3. 一旦 with 块完成,它会关闭新的 file_handle 吗?

如果你问这个问题,你应该重构你的代码,这样这些类型的歧义就不存在了。实际上有无限多的可能变量名,如果您为第二个文件句柄选择不同的名称,这个问题就会消失。

with open('some/file') as file_handle:
  # some codes
  with open('another/file') as file_handle_2:
    # more codes

或者,如果您不需要同时使用两个文件句柄,请使用两个单独的 "with" 块,以便第一个在第二个打开之前关闭:

with open('some/file') as file_handle:
  # some codes
with open('another/file') as file_handle_2:
  # more codes

What would happen to the first file_handle? Would it be closed after assignment or it remains open?

它一直打开到 with 块结束。

If after the assignment, an exception happened in the with block, would the newly opened file be closed or not?

没有。 with 块控制第一个文件对象,没有任何内容明确跟踪第二个文件对象。

Once the with block is finished, does it close the new file_handle?

不,它会被泄露,除非垃圾收集器注意到它未被使用并为您关闭它。

with 关键字是缩写 try except block

"If you’re not using the with keyword, then you should call f.close() to close the file and immediately free up any system resources used by it."