diff options
author | Andrew Svetlov <andrew.svetlov@gmail.com> | 2012-11-29 12:20:47 (GMT) |
---|---|---|
committer | Andrew Svetlov <andrew.svetlov@gmail.com> | 2012-11-29 12:20:47 (GMT) |
commit | 718df1d6384da5285e5c2e5cab6584bf10350513 (patch) | |
tree | 90151e35c42b38f6d6126e9803fbeed6ba1f4291 | |
parent | 4927633ab6c6895621d88d51ae2d7943426e2c04 (diff) | |
download | cpython-718df1d6384da5285e5c2e5cab6584bf10350513.zip cpython-718df1d6384da5285e5c2e5cab6584bf10350513.tar.gz cpython-718df1d6384da5285e5c2e5cab6584bf10350513.tar.bz2 |
Issue #16477: Close tarfile internal handlers in case of exception.
Patch by Serhiy Storchaka.
-rw-r--r-- | Lib/tarfile.py | 24 |
1 files changed, 11 insertions, 13 deletions
diff --git a/Lib/tarfile.py b/Lib/tarfile.py index f26953e..54d0e0e 100644 --- a/Lib/tarfile.py +++ b/Lib/tarfile.py @@ -2077,9 +2077,8 @@ class TarFile(object): # Append the tar header and data to the archive. if tarinfo.isreg(): - f = bltn_open(name, "rb") - self.addfile(tarinfo, f) - f.close() + with bltn_open(name, "rb") as f: + self.addfile(tarinfo, f) elif tarinfo.isdir(): self.addfile(tarinfo) @@ -2292,16 +2291,15 @@ class TarFile(object): """ source = self.fileobj source.seek(tarinfo.offset_data) - target = bltn_open(targetpath, "wb") - if tarinfo.sparse is not None: - for offset, size in tarinfo.sparse: - target.seek(offset) - copyfileobj(source, target, size) - else: - copyfileobj(source, target, tarinfo.size) - target.seek(tarinfo.size) - target.truncate() - target.close() + with bltn_open(targetpath, "wb") as target: + if tarinfo.sparse is not None: + for offset, size in tarinfo.sparse: + target.seek(offset) + copyfileobj(source, target, size) + else: + copyfileobj(source, target, tarinfo.size) + target.seek(tarinfo.size) + target.truncate() def makeunknown(self, tarinfo, targetpath): """Make a file from a TarInfo object with an unknown type |