diff options
author | Andrew Svetlov <andrew.svetlov@gmail.com> | 2012-11-29 12:21:39 (GMT) |
---|---|---|
committer | Andrew Svetlov <andrew.svetlov@gmail.com> | 2012-11-29 12:21:39 (GMT) |
commit | 7030dd8500dc7c040878d7c089e43a4dad62d393 (patch) | |
tree | 10b07af3762e26b38003fe028b851d08a242034c /Lib/tarfile.py | |
parent | 63cd0aa5696f9e8220e615369324272136b8ca2e (diff) | |
parent | 7ecd13da5f16ff91153167c8fd77a901bda88bbf (diff) | |
download | cpython-7030dd8500dc7c040878d7c089e43a4dad62d393.zip cpython-7030dd8500dc7c040878d7c089e43a4dad62d393.tar.gz cpython-7030dd8500dc7c040878d7c089e43a4dad62d393.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 a88224d..93e6cd9 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 |