diff --git a/pygmt/figure.py b/pygmt/figure.py index c3159b5d79f..76d0b617bee 100644 --- a/pygmt/figure.py +++ b/pygmt/figure.py @@ -4,6 +4,7 @@ import base64 import os import warnings +from pathlib import Path from tempfile import TemporaryDirectory try: @@ -251,6 +252,13 @@ def psconvert(self, icc_gray=False, **kwargs): ) prefix_arg = f'-F"{prefix}"' + # check if the parent directory exists + prefix_path = Path(prefix).parent + if not prefix_path.exists(): + raise FileNotFoundError( + f"No such directory: '{prefix_path}', please create it first." + ) + with Session() as lib: lib.call_module( module="psconvert", args=f"{prefix_arg} {build_arg_string(kwargs)}" diff --git a/pygmt/tests/test_figure.py b/pygmt/tests/test_figure.py index 2d5949eaddb..900c70d74ad 100644 --- a/pygmt/tests/test_figure.py +++ b/pygmt/tests/test_figure.py @@ -89,6 +89,17 @@ def test_figure_savefig_exists(): os.remove(fname) +def test_figure_savefig_directory_nonexists(): + """ + Make sure that Figure.savefig() raises a FileNotFoundError when the parent + directory doesn't exist. + """ + fig = Figure() + fig.basemap(region="10/70/-300/800", projection="X3i/5i", frame="af") + with pytest.raises(FileNotFoundError, match="No such directory:"): + fig.savefig("a-nonexist-directory/test_figure_savefig_directory_nonexists.png") + + def test_figure_savefig_unknown_extension(): """ Check that an error is raised when an unknown extension is passed.