diff options
author | Andrew Svetlov <andrew.svetlov@gmail.com> | 2012-11-29 12:21:23 (GMT) |
---|---|---|
committer | Andrew Svetlov <andrew.svetlov@gmail.com> | 2012-11-29 12:21:23 (GMT) |
commit | 7ecd13da5f16ff91153167c8fd77a901bda88bbf (patch) | |
tree | 7e8b28461dab0eacf612b9ce8bd50684d3f074ea /Lib/tarfile.py | |
parent | 159f12e3350f0986e57a1b86017d8f189f43fef9 (diff) | |
parent | 718df1d6384da5285e5c2e5cab6584bf10350513 (diff) | |
download | cpython-7ecd13da5f16ff91153167c8fd77a901bda88bbf.zip cpython-7ecd13da5f16ff91153167c8fd77a901bda88bbf.tar.gz cpython-7ecd13da5f16ff91153167c8fd77a901bda88bbf.tar.bz2 |
Merge issue #16477: Close tarfile internal handlers in case of exception.
Patch by Serhiy Storchaka.
Diffstat (limited to 'Lib/tarfile.py')
-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 7b9f407..11b4b68 100644 --- a/Lib/tarfile.py +++ b/Lib/tarfile.py @@ -1924,9 +1924,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) @@ -2131,16 +2130,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 |