json.load python 中文件的等效方法?
Equivalent ways to json.load a file in python?
我经常在代码中看到这个:
with open(file_path) as f:
json_content = json.load(f)
这种情况较少:
json_content = json.load(open(file_path))
我想知道后者是反模式还是两个版本有什么区别
当您使用上下文管理器时,它保证您的文件将在块结束时自动关闭。 with
statement 通过使用其 __exit__()
方法调用文件对象的 close
属性来实现这一点。
如文档中所述:
The with statement guarantees that if the __enter__()
method returns
without an error, then __exit__()
will always be called.
了解更多功能https://docs.python.org/3.5/reference/compound_stmts.html#with
除了其他答案之外,上下文管理器与 try-finally 子句非常相似。
此代码:
with open(file_path) as f:
json_content = json.load(f)
可以写成:
f = open(file_path)
try:
json_content = json.load(f)
finally:
f.close()
前者显然更可取。
json.load(open(file_path))
依靠 GC 来关闭文件。这不是一个好主意:如果有人不使用 CPython,垃圾收集器可能不会使用引用计数(它会立即收集未引用的对象),但是例如一段时间后才收集垃圾。
由于当关联对象被垃圾回收或显式关闭(.close()
或 .__exit__()
来自上下文管理器)时文件句柄关闭,文件将保持打开状态直到 GC 启动。
使用 with
确保文件在块离开后立即关闭 - 即使在该块内发生异常,因此它应该始终是任何实际应用程序的首选。
我经常在代码中看到这个:
with open(file_path) as f:
json_content = json.load(f)
这种情况较少:
json_content = json.load(open(file_path))
我想知道后者是反模式还是两个版本有什么区别
当您使用上下文管理器时,它保证您的文件将在块结束时自动关闭。 with
statement 通过使用其 __exit__()
方法调用文件对象的 close
属性来实现这一点。
如文档中所述:
The with statement guarantees that if the
__enter__()
method returns without an error, then__exit__()
will always be called.
了解更多功能https://docs.python.org/3.5/reference/compound_stmts.html#with
除了其他答案之外,上下文管理器与 try-finally 子句非常相似。
此代码:
with open(file_path) as f:
json_content = json.load(f)
可以写成:
f = open(file_path)
try:
json_content = json.load(f)
finally:
f.close()
前者显然更可取。
json.load(open(file_path))
依靠 GC 来关闭文件。这不是一个好主意:如果有人不使用 CPython,垃圾收集器可能不会使用引用计数(它会立即收集未引用的对象),但是例如一段时间后才收集垃圾。
由于当关联对象被垃圾回收或显式关闭(.close()
或 .__exit__()
来自上下文管理器)时文件句柄关闭,文件将保持打开状态直到 GC 启动。
使用 with
确保文件在块离开后立即关闭 - 即使在该块内发生异常,因此它应该始终是任何实际应用程序的首选。