Python 3 gzip 会关闭 fileobj 吗? [英] Does Python 3 gzip closes the fileobj?

查看:46
本文介绍了Python 3 gzip 会关闭 fileobj 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3 的 gzip 文档 表示

The gzip docs for Python 3 states that

调用 GzipFile 对象的 close() 方法不会关闭 fileobj,因为您可能希望在压缩数据后附加更多材料

Calling a GzipFile object’s close() method does not close fileobj, since you might wish to append more material after the compressed data

这是否意味着如果我们执行以下操作,gzip 文件处理程序 f_in 不会关闭

Does this mean that the gzip file handler f_in is not closed if we do the following

import gzip
import shutil
with gzip.open('/home/joe/file.txt.gz', 'rb') as f_in:
    with open('/home/joe/file.txt', 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)

如果是这样,如果多次执行此代码会导致泄漏吗?

If so, will this cause a leak if this code is executed multiple times?

推荐答案

fileobj 未关闭的警告仅适用于打开文件并通过 fileobj= 参数将其传递给 GzipFile.当您仅传递文件名时,GzipFile 拥有"文件句柄,也将关闭它.

The warning about fileobj not being closed only applies when you open the file, and pass it to the GzipFile via the fileobj= parameter. When you pass only a filename, GzipFile "owns" the file handle and will also close it.

这篇关于Python 3 gzip 会关闭 fileobj 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆