GridFS:对于使用'put'编写文件,是否需要显式'with'块?

问题描述 投票:0回答:1

要使用put()在gridFS中编写大文件,是否有必要使用上下文管理器with?查看put() here的文档,调用put()相当于做,

try:
    f = new_file(**kwargs)
    f.write(data)
finally:
    f.close()

这是否意味着文件的打开和关闭是自动完成的,因此在没有明确需要的情况下不需要?

python mongodb pymongo gridfs
1个回答
0
投票

gridfs.GridFS.put isn't a context manager。它没有定义上下文管理协议的__enter____exit__方法。

直接使用它而不作为上下文管理器的一些修改将导致AttributeError

使用gridfs.GridFS.put as-is可以节省几行代码,更重要的是必须管理打开和关闭GridFile

© www.soinside.com 2019 - 2024. All rights reserved.