Issue #16477: Close tarfile internal handlers in case of exception.
authorAndrew Svetlov <andrew.svetlov@gmail.com>
Thu, 29 Nov 2012 12:20:47 +0000 (14:20 +0200)
committerAndrew Svetlov <andrew.svetlov@gmail.com>
Thu, 29 Nov 2012 12:20:47 +0000 (14:20 +0200)
Patch by Serhiy Storchaka.

Lib/tarfile.py

index f26953e2bb1f69ddeb91575ceedc23685f6ebf77..54d0e0e173f444c51997a8d7579bf1e692f2de4a 100644 (file)
@@ -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