Patch #1517891: Make 'a' create the file if it doesn't exist.
Fixes #1514451.
diff --git a/Lib/test/test_zipfile.py b/Lib/test/test_zipfile.py
index 2d206df..c17039f 100644
--- a/Lib/test/test_zipfile.py
+++ b/Lib/test/test_zipfile.py
@@ -307,6 +307,28 @@
class OtherTests(unittest.TestCase):
+ def testCreateNonExistentFileForAppend(self):
+ if os.path.exists(TESTFN):
+ os.unlink(TESTFN)
+
+ filename = 'testfile.txt'
+ content = 'hello, world. this is some content.'
+
+ try:
+ zf = zipfile.ZipFile(TESTFN, 'a')
+ zf.writestr(filename, content)
+ zf.close()
+ except IOError, (errno, errmsg):
+ self.fail('Could not append data to a non-existent zip file.')
+
+ self.assert_(os.path.exists(TESTFN))
+
+ zf = zipfile.ZipFile(TESTFN, 'r')
+ self.assertEqual(zf.read(filename), content)
+ zf.close()
+
+ os.unlink(TESTFN)
+
def testCloseErroneousFile(self):
# This test checks that the ZipFile constructor closes the file object
# it opens if there's an error in the file. If it doesn't, the traceback
diff --git a/Lib/zipfile.py b/Lib/zipfile.py
index 93a0b75..6e59242 100644
--- a/Lib/zipfile.py
+++ b/Lib/zipfile.py
@@ -396,7 +396,14 @@
self._filePassed = 0
self.filename = file
modeDict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'}
- self.fp = open(file, modeDict[mode])
+ try:
+ self.fp = open(file, modeDict[mode])
+ except IOError:
+ if mode == 'a':
+ mode = key = 'w'
+ self.fp = open(file, modeDict[mode])
+ else:
+ raise
else:
self._filePassed = 1
self.fp = file