diff --git a/tiatoolbox/utils/misc.py b/tiatoolbox/utils/misc.py index 5ec83b170..89e60970e 100644 --- a/tiatoolbox/utils/misc.py +++ b/tiatoolbox/utils/misc.py @@ -3,6 +3,8 @@ import copy import json +import shutil +import tempfile import zipfile from pathlib import Path from typing import IO, TYPE_CHECKING @@ -714,9 +716,13 @@ def download_data( # Raise an exception for status codes != 200 response.raise_for_status() # Write the file in blocks of 1024 bytes to avoid running out of memory - with save_path.open("wb") as handle: + + with tempfile.NamedTemporaryFile(mode="wb", delete=False) as templ_file: for block in response.iter_content(1024): - handle.write(block) + templ_file.write(block) + + # Move the temporary file to the desired location + shutil.move(templ_file.name, save_path) if unzip: unzip_path = save_dir / save_path.stem