文本文件或 json 文件如何以及何时关闭?

How and when does a text file or json file get closed?

我在访问通过 json 打开的字典时遇到了一些错误,并且在阅读这里时发现我试图访问(从文本文件)的字典已关闭。在我正在做的这个简化版本中,文件是如何关闭的?

代码:

import json

with open('nID.txt') as json_file:
    data = json.load(json_file)
    print(data)
    print('R1N1x       :', data['R1N1']['x'])
    print('R1N1y       :',  data['R1N1']['y'])
    print('R1N500x     :', data['R1N500']['x'])
    print('R1N500y     :', data['R1N500']['y'])
    print('R2N1x       :', data['R2N1']['x'])
    print('R2N1y       :',  data['R2N1']['y'])
    print('R2N500x     :', data['R2N500']['x'])
    print('R2N500y     :', data['R2N500']['y'])





if json_file.closed:
  print('file is closed')

在本例中,with 语句会在套件结束时自动关闭变量或文件,

如果您不希望出现这种情况,请删除 with 语句并以 json_file.close()

结尾

我相信3.4中添加了with语句

这是文档:

https://docs.python.org/2.5/whatsnew/pep-343.html

对于所有语句:

https://docs.python.org/3/reference/compound_stmts.html