gpt4 book ai didi

python - with block 或 close() 更 Pythonic 吗?

转载 作者:太空宇宙 更新时间:2023-11-04 00:35:31 29 4
gpt4 key购买 nike

据我所知,with block 会在您退出 block 后自动调用 close(),并且它通常用于确保不会忘记关闭一个文件。

好像没有技术上的区别

with open(file, 'r+') as f:
do_things(f)

f = open(file, 'r+')
do_things(f)
f.close()

有一种方式比另一种方式更 Pythonic 吗?我应该在我的代码中使用哪个?

最佳答案

Is one way more Pythonic than the other?

是的,with语句形式是首选,它将文件管理逻辑封装到一行代码中。这提高了业务逻辑与管理逻辑的比率,使程序更易于阅读和推理。

根据 PEP 343 , with 语句的预期目的是:

This PEP adds a new statement "with" to the Python language to make
it possible to factor out standard uses of try/finally statements.

关于python - with block 或 close() 更 Pythonic 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44223150/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com