diff -r 07ee5004656a Lib/dbm/__init__.py --- a/Lib/dbm/__init__.py Mon Mar 14 12:37:25 2011 -0400 +++ b/Lib/dbm/__init__.py Mon Mar 14 13:26:34 2011 -0400 @@ -67,10 +67,10 @@ if not _defaultmod: raise ImportError("no dbm clone found; tried %s" % _names) - # guess the type of an existing database - result = whichdb(file) + # guess the type of an existing database, if not creating a new one + result = whichdb(file) if 'n' not in flag else None if result is None: - # db doesn't exist + # db doesn't exist or 'n' flag was specified to create a new db if 'c' in flag or 'n' in flag: # file doesn't exist and the new flag was used so use default type mod = _defaultmod diff -r 07ee5004656a Lib/test/test_dbm.py --- a/Lib/test/test_dbm.py Mon Mar 14 12:37:25 2011 -0400 +++ b/Lib/test/test_dbm.py Mon Mar 14 13:26:34 2011 -0400 @@ -70,6 +70,14 @@ self.read_helper(f) f.close() + def test_anydbm_creation_n_file_exists_with_invalid_contents(self): + with open(_fname, "w") as w: + pass # create an empty file + + f = dbm.open(_fname, 'n') + self.addCleanup(f.close) + self.assertEqual(len(f), 0) + def test_anydbm_modification(self): self.init_db() f = dbm.open(_fname, 'c')