使用with open仍触发ResourceWarning: unclosed file问题求助
问题分析与解决:ResourceWarning 未关闭文件警告
错误信息
ResourceWarning: unclosed file <_io.BufferedReader name='/home/idris/Documents/workspace/captiq/captiq/static/docs/CAPTIQ Datenschutzhinweise.pdf'> attachment=customer_profile.get_attachments(), ResourceWarning: Enable tracemalloc to get the object allocation traceback
问题代码段
with open(path_one, 'rb') as f1, open(path_two, 'rb') as f2: files = [f1, f2] attachments = [ { 'filename': os.path.basename(attachment.name), 'content': attachment.read(), 'mimetype': mimetypes.guess_type(attachment.name)[0] } for attachment in files] return attachments
原因分析
虽然用with open管理了文件上下文,但代码把文件对象f1、f2存入了files列表。即便在with块内完成了读操作,文件对象的引用会被files列表持有,可能因Python垃圾回收时机延迟,导致文件未能被即时关闭,触发ResourceWarning。
解决方案
修改代码,不保留文件对象的引用,直接用文件路径生成文件名和MIME类型,在with块内完成所有文件操作并构建结果:
if not files: path_one = finders.find('docs/file_1.pdf') path_two = finders.find('docs/file_2.pdf') attachments = [] # 逐个处理文件,避免持有文件对象引用 with open(path_one, 'rb') as f1: attachments.append({ 'filename': os.path.basename(path_one), 'content': f1.read(), 'mimetype': mimetypes.guess_type(path_one)[0] }) with open(path_two, 'rb') as f2: attachments.append({ 'filename': os.path.basename(path_two), 'content': f2.read(), 'mimetype': mimetypes.guess_type(path_two)[0] }) return attachments
额外提示
错误信息中提到的文件是CAPTIQ Datenschutzhinweise.pdf,但当前问题代码段处理的是file_1.pdf和file_2.pdf,建议同时检查get_default_attachments()方法及合作伙伴附件分支的文件操作,确保所有文件对象都被正确关闭(比如Django的File对象是否需要手动调用close(),或者是否存在未使用上下文管理器的文件操作)。
内容的提问来源于stack exchange,提问作者Lutaaya Huzaifah Idris
相关产品推荐
相关产品推荐

