[Python-checkins] cpython (merge 3.2 -> 3.3): Merge issue #16477: Close tarfile internal handlers in case of exception.

andrew.svetlov python-checkins at python.org
Thu Nov 29 13:22:44 CET 2012


http://hg.python.org/cpython/rev/80749ddc30b6
changeset:   80649:80749ddc30b6
branch:      3.3
parent:      80646:e26345437f9f
parent:      80648:b7bdc0b3c2fe
user:        Andrew Svetlov <andrew.svetlov at gmail.com>
date:        Thu Nov 29 14:21:23 2012 +0200
summary:
  Merge issue #16477: Close tarfile internal handlers in case of exception.

Patch by Serhiy Storchaka.

files:
  Lib/tarfile.py |  24 +++++++++++-------------
  1 files changed, 11 insertions(+), 13 deletions(-)


diff --git a/Lib/tarfile.py b/Lib/tarfile.py
--- a/Lib/tarfile.py
+++ b/Lib/tarfile.py
@@ -1924,9 +1924,8 @@
 
         # 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 @@
         """
         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

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list