首页 > 解决方案 > Python中有没有办法不使用with语句,也不需要手动调用.close?

问题描述

Python打开文件时,您应该这样做:

# automatically calls .close method on exit from the with statement
with open("my_file.txt", "r") as f:
    ...

或这个:

try:
    f = open("my_file.txt", "r")
    ...
except:
    ...
finally:
    f.close()

但是,我想要这样的东西。

f = open("my_file.txt", "r")
# operate with the file
...
# file is not going to be referenced anymore
# or there has been an exception
# close the file but without manually calling the f.close method

我知道垃圾收集器可能会关闭文件,但我想明确地这样做而不手动执行或执行with语句。

有没有办法使用任何magic类方法或使用contextlib库或任何其他库来做到这一点?

用例

我想要这样的原因是因为我在不同httpx.AsyncClientpython模块中functions使用script. 我不想将httpx.AsyncClient实例作为参数传递给每个函数,而是在脚本开始时将其定义一次,如果出现故障(异常等),则会自动关闭它。

标签: python

解决方案


警告

我将保留答案,因为它回答了原始问题。但是任何看到这个的人都应该被警告它不适用于异步。您可以在下面的评论中看到有关此的更多详细信息

使用atexit 模块可能吗?

import atexit

f = open("my_file.txt", "r")

@atexit.register
def closefile():
    f.close()

# operate with the file
# ...

推荐阅读