Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

If an error occurs after creating a file, remove the file #6134

Merged
merged 1 commit into from Mar 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions Tests/test_image.py
Expand Up @@ -652,6 +652,15 @@ def test_no_resource_warning_on_save(self, tmp_path):
with warnings.catch_warnings():
im.save(temp_file)

def test_no_new_file_on_error(self, tmp_path):
temp_file = str(tmp_path / "temp.jpg")

im = Image.new("RGB", (0, 0))
with pytest.raises(SystemError):
im.save(temp_file)

assert not os.path.exists(temp_file)

def test_load_on_nonexclusive_multiframe(self):
with open("Tests/images/frozenpond.mpo", "rb") as fp:

Expand Down
13 changes: 11 additions & 2 deletions src/PIL/Image.py
Expand Up @@ -2286,7 +2286,9 @@ def save(self, fp, format=None, **params):
else:
save_handler = SAVE[format.upper()]

created = False
if open_fp:
created = not os.path.exists(filename)
if params.get("append", False):
# Open also for reading ("+"), because TIFF save_all
# writer needs to go back and edit the written data.
Expand All @@ -2296,10 +2298,17 @@ def save(self, fp, format=None, **params):

try:
save_handler(self, fp, filename)
finally:
# do what we can to clean up
except Exception:
if open_fp:
fp.close()
if created:
try:
os.remove(filename)
except PermissionError:
pass
raise
if open_fp:
fp.close()

def seek(self, frame):
"""
Expand Down