【问题标题】:Is it necessary to close the file in json.load?需要关闭json.load中的文件吗?
【发布时间】:2018-05-17 21:19:28
【问题描述】:

很明显,应该关闭文件对象才能将其从内存中删除:

file = open('data.txt', 'r')
#more code here
file.close()

是否还需要关闭提供给json.load 方法的文件对象?

data = json.load(open('data.json','r'))

我猜不是,因为文件对象没有存储在变量中,但是如果是,怎么办?

【问题讨论】:

  • 不幸的是,您的问题的第二部分从未得到回答,我也想知道如何做到这一点,如果可以的话。

标签: python json file


【解决方案1】:

不要依赖 GC 来清理/关闭文件描述符。 请改用context manager

您也不需要提供'r' 模式,因为它是open 的默认模式。

with open('data.json') as f:
    data = json.load(f)

【讨论】:

  • Don't rely on the GC to clean/close the file descriptor你是说GC从不关闭文件还是不确定是否会关闭。
  • @multigoodverse 我的意思是当你期望它会关闭文件时,你不能依赖 GC。
【解决方案2】:

对我来说,关闭一个 json 文件就像在 python 中处理普通文件一样。

文件名.close()

【讨论】:

  • 这并没有回答 OP 提出的问题 Is it necessary 关闭文件json.load?
猜你喜欢
  • 2019-08-01
  • 1970-01-01
  • 2015-01-18
  • 2013-01-10
  • 2013-03-06
  • 2020-06-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多