简体   繁体   English

在python中json.load文件的等效方法?

[英]Equivalent ways to json.load a file in python?

I often see this in code:我经常在代码中看到这一点:

with open(file_path) as f:
    json_content = json.load(f)

And less often this:很少有这样的:

json_content = json.load(open(file_path))

I was wondering if the latter is an anti pattern or what the difference between the two versions is.我想知道后者是一种反模式还是两个版本之间的区别是什么。

When you use a context manager, it guarantees that your file will be close automatically at the end of block.当您使用上下文管理器时,它保证您的文件将在块的末尾自动关闭。 The with statement does this by calling the close attribute of the file object, using its __exit__() method. with语句通过使用其__exit__()方法调用文件对象的close属性来完成此操作。

As said in document:正如文档中所说:

The with statement guarantees that if the __enter__() method returns without an error, then __exit__() will always be called.该声明与保证,如果__enter__()方法返回没有错误,那么__exit__()总是会被调用。

Read about more features https://docs.python.org/3.5/reference/compound_stmts.html#with阅读更多功能https://docs.python.org/3.5/reference/compound_stmts.html#with

json.load(open(file_path)) relies on the GC to close the file. json.load(open(file_path))依赖 GC 来关闭文件。 That's not a good idea: If someone doesn't use CPython the garbage collector might not be using refcounting (which collects unreferenced objects immediately) but eg collect garbage only after some time.这不是一个好主意:如果有人不使用 CPython,垃圾收集器可能不会使用 refcounting(它立即收集未引用的对象),而是仅在一段时间后收集垃圾。

Since file handles are closed when the associated object is garbage collected or closed explicitly ( .close() or .__exit__() from a context manager) the file will remain open until the GC kicks in.由于当关联对象被垃圾收集或显式关闭.__exit__()来自上下文管理器的.close().__exit__()时,文件句柄将关闭,因此文件将保持打开状态,直到 GC 启动。

Using with ensures the file is closed as soon as the block is left - even if an exception happens inside that block, so it should always be preferred for any real application.使用with确保文件在块离开时立即关闭 - 即使在该块内发生异常,因此对于任何实际应用程序来说,它应该始终是首选。

In addition to other answers, a context manager is very similar to the try-finally clause.除了其他答案之外,上下文管理器与 try-finally 子句非常相似。

This code:这段代码:

with open(file_path) as f:
    json_content = json.load(f)

can be written as:可以写成:

f = open(file_path)
try:
    json_content = json.load(f)
finally:
    f.close()

The former is clearly preferable.前者显然更可取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM