R1732:考虑使用 'with' 进行资源分配操作(consider-using-with)

R1732: Consider using 'with' for resource-allocating operations (consider-using-with)

我是 运行 pylint,用于在我的项目中检测错误,偶然发现了这个警告。 我该如何修复此警告?

假设您正在打开一个文件:

file_handle = open("some_file.txt", "r")
...
...
file_handle.close()

完成所需任务后,您需要手动关闭该文件。如果它没有关闭,那么资源(在本例中为memory/buffer)就被浪费了。


如果你在上面的例子中使用with

with open("some_file.txt", "r") as file_handle:
    ...
    ...

无需关闭该文件。使用 with.

时会自动取消资源分配