From dc4acc5b37b8693ed6a41fc57604262f3c989969 Mon Sep 17 00:00:00 2001 From: Dongdong Tian Date: Mon, 18 Mar 2024 14:15:44 +0800 Subject: [PATCH] Migrate from os.path to pathlib --- examples/gallery/images/image.py | 4 ++-- examples/tutorials/basics/text.py | 4 ++-- pygmt/figure.py | 6 +++--- pygmt/helpers/tempfile.py | 9 ++++----- pygmt/helpers/testing.py | 15 +++++++-------- pygmt/src/grdfilter.py | 4 ++-- pygmt/src/x2sys_cross.py | 2 +- pygmt/tests/test_accessor.py | 3 +-- pygmt/tests/test_figure.py | 4 ++-- pygmt/tests/test_helpers.py | 5 +++-- pygmt/tests/test_psconvert.py | 14 +++++++------- pygmt/tests/test_session_management.py | 15 +++++++-------- pygmt/tests/test_sphinx_gallery.py | 5 +++-- pygmt/tests/test_x2sys_cross.py | 2 +- 14 files changed, 45 insertions(+), 47 deletions(-) diff --git a/examples/gallery/images/image.py b/examples/gallery/images/image.py index 52d6b197fa5..1806ae55577 100644 --- a/examples/gallery/images/image.py +++ b/examples/gallery/images/image.py @@ -11,7 +11,7 @@ """ # %% -import os +from pathlib import Path import pygmt @@ -28,6 +28,6 @@ ) # clean up the downloaded image in the current directory -os.remove("gmt-logo.png") +Path("gmt-logo.png").unlink() fig.show() diff --git a/examples/tutorials/basics/text.py b/examples/tutorials/basics/text.py index 4ad92091de1..1f225bb39c3 100644 --- a/examples/tutorials/basics/text.py +++ b/examples/tutorials/basics/text.py @@ -7,7 +7,7 @@ """ # %% -import os +from pathlib import Path import pygmt @@ -88,7 +88,7 @@ fig.text(textfiles="examples.txt", angle=True, font=True, justify=True) # Cleanups -os.remove("examples.txt") +Path("examples.txt").unlink() fig.show() diff --git a/pygmt/figure.py b/pygmt/figure.py index 98f06291c6b..523933fbabe 100644 --- a/pygmt/figure.py +++ b/pygmt/figure.py @@ -67,10 +67,10 @@ class Figure: >>> fig.basemap(region=[0, 360, -90, 90], projection="W15c", frame=True) >>> fig.savefig("my-figure.png") >>> # Make sure the figure file is generated and clean it up - >>> import os - >>> os.path.exists("my-figure.png") + >>> from pathlib import Path + >>> Path("my-figure.png").exists() True - >>> os.remove("my-figure.png") + >>> Path("my-figure.png").unlink() The plot region can be specified through ISO country codes (for example, ``"JP"`` for Japan): diff --git a/pygmt/helpers/tempfile.py b/pygmt/helpers/tempfile.py index 62a3daf5447..bed79f352ae 100644 --- a/pygmt/helpers/tempfile.py +++ b/pygmt/helpers/tempfile.py @@ -2,9 +2,9 @@ Utilities for dealing with temporary file management. """ -import os import uuid from contextlib import contextmanager +from pathlib import Path from tempfile import NamedTemporaryFile import numpy as np @@ -72,8 +72,7 @@ def __exit__(self, *args): """ Remove the temporary file. """ - if os.path.exists(self.name): - os.remove(self.name) + Path(self.name).unlink(missing_ok=True) def read(self, keep_tabs=False): """ @@ -133,7 +132,7 @@ def tempfile_from_geojson(geojson): with GMTTempFile(suffix=".gmt") as tmpfile: import geopandas as gpd - os.remove(tmpfile.name) # ensure file is deleted first + Path(tmpfile.name).unlink() # Ensure file is deleted first ogrgmt_kwargs = {"filename": tmpfile.name, "driver": "OGR_GMT", "mode": "w"} try: # OGR_GMT only supports 32-bit integers. We need to map int/int64 @@ -185,7 +184,7 @@ def tempfile_from_image(image): A temporary GeoTIFF file holding the image data. E.g. '1a2b3c4d5.tif'. """ with GMTTempFile(suffix=".tif") as tmpfile: - os.remove(tmpfile.name) # ensure file is deleted first + Path(tmpfile.name).unlink() # Ensure file is deleted first try: image.rio.to_raster(raster_path=tmpfile.name) except AttributeError as e: # object has no attribute 'rio' diff --git a/pygmt/helpers/testing.py b/pygmt/helpers/testing.py index 1a1c72cb334..93cc93ea341 100644 --- a/pygmt/helpers/testing.py +++ b/pygmt/helpers/testing.py @@ -6,6 +6,7 @@ import inspect import os import string +from pathlib import Path from pygmt.exceptions import GMTImageComparisonFailure from pygmt.io import load_dataarray @@ -39,6 +40,7 @@ def check_figures_equal(*, extensions=("png",), tol=0.0, result_dir="result_imag >>> import pytest >>> import shutil >>> from pygmt import Figure + >>> from pathlib import Path >>> @check_figures_equal(result_dir="tmp_result_images") ... def test_check_figures_equal(): @@ -63,12 +65,9 @@ def check_figures_equal(*, extensions=("png",), tol=0.0, result_dir="result_imag >>> with pytest.raises(GMTImageComparisonFailure): ... test_check_figures_unequal() >>> for suffix in ["", "-expected", "-failed-diff"]: - ... assert os.path.exists( - ... os.path.join( - ... "tmp_result_images", - ... f"test_check_figures_unequal{suffix}.png", - ... ) - ... ) + ... assert Path( + ... f"tmp_result_image/test_check_figures_unequal{suffix}.png" + ... ).exists() >>> shutil.rmtree(path="tmp_result_images") # cleanup folder if tests pass """ allowed_chars = set(string.digits + string.ascii_letters + "_-[]()") @@ -107,8 +106,8 @@ def wrapper(*args, ext="png", request=None, **kwargs): in_decorator=True, ) if err is None: # Images are the same - os.remove(ref_image_path) - os.remove(test_image_path) + Path(ref_image_path).unlink() + Path(test_image_path).unlink() else: # Images are not the same for key in ["actual", "expected", "diff"]: err[key] = os.path.relpath(err[key]) diff --git a/pygmt/src/grdfilter.py b/pygmt/src/grdfilter.py index a4a544819ad..a6e49c65001 100644 --- a/pygmt/src/grdfilter.py +++ b/pygmt/src/grdfilter.py @@ -114,7 +114,7 @@ def grdfilter(grid, **kwargs): Examples -------- - >>> import os + >>> from pathlib import Path >>> import pygmt >>> # Apply a filter of 600 km (full width) to the @earth_relief_30m_g file >>> # and return a filtered field (saved as netCDF) @@ -126,7 +126,7 @@ def grdfilter(grid, **kwargs): ... spacing=0.5, ... outgrid="filtered_pacific.nc", ... ) - >>> os.remove("filtered_pacific.nc") # Cleanup file + >>> Path("filtered_pacific.nc").unlink() # Cleanup file >>> # Apply a Gaussian smoothing filter of 600 km to the input DataArray >>> # and return a filtered DataArray with the smoothed field >>> grid = pygmt.datasets.load_earth_relief() diff --git a/pygmt/src/x2sys_cross.py b/pygmt/src/x2sys_cross.py index a8988a00af8..c530c964025 100644 --- a/pygmt/src/x2sys_cross.py +++ b/pygmt/src/x2sys_cross.py @@ -53,7 +53,7 @@ def tempfile_from_dftrack(track, suffix): ) yield tmpfilename finally: - os.remove(tmpfilename) + Path(tmpfilename).unlink() @fmt_docstring diff --git a/pygmt/tests/test_accessor.py b/pygmt/tests/test_accessor.py index a12c01e9265..ed047c2ec28 100644 --- a/pygmt/tests/test_accessor.py +++ b/pygmt/tests/test_accessor.py @@ -2,7 +2,6 @@ Test the behaviour of the GMTDataArrayAccessor class. """ -import os import sys from pathlib import Path @@ -101,7 +100,7 @@ def test_accessor_sliced_datacube(): assert grid.gmt.registration == 0 # gridline registration assert grid.gmt.gtype == 1 # geographic coordinate type finally: - os.remove(fname) + Path(fname).unlink() def test_accessor_grid_source_file_not_exist(): diff --git a/pygmt/tests/test_figure.py b/pygmt/tests/test_figure.py index d33be107eda..7d653d40f78 100644 --- a/pygmt/tests/test_figure.py +++ b/pygmt/tests/test_figure.py @@ -203,8 +203,8 @@ def test_figure_savefig_transparent(): # png should not raise an error fname = f"{prefix}.png" fig.savefig(fname, transparent=True) - assert os.path.exists(fname) - os.remove(fname) + assert Path(fname).exists() + Path(fname).unlink() def test_figure_savefig_filename_with_spaces(): diff --git a/pygmt/tests/test_helpers.py b/pygmt/tests/test_helpers.py index 29cc61fe8b7..57d8b8159a9 100644 --- a/pygmt/tests/test_helpers.py +++ b/pygmt/tests/test_helpers.py @@ -3,6 +3,7 @@ """ import os +from pathlib import Path import numpy as np import pytest @@ -90,9 +91,9 @@ def test_gmttempfile(): Check that file is really created and deleted. """ with GMTTempFile() as tmpfile: - assert os.path.exists(tmpfile.name) + assert Path(tmpfile.name).exists() # File should be deleted when leaving the with block - assert not os.path.exists(tmpfile.name) + assert not Path(tmpfile.name).exists() def test_gmttempfile_unique(): diff --git a/pygmt/tests/test_psconvert.py b/pygmt/tests/test_psconvert.py index 6cc82cc50e9..77b47c8e24b 100644 --- a/pygmt/tests/test_psconvert.py +++ b/pygmt/tests/test_psconvert.py @@ -2,7 +2,7 @@ Test Figure.psconvert. """ -import os +from pathlib import Path import pytest from pygmt import Figure @@ -19,8 +19,8 @@ def test_psconvert(): prefix = "test_psconvert" fig.psconvert(prefix=prefix, fmt="f", crop=True) fname = prefix + ".pdf" - assert os.path.exists(fname) - os.remove(fname) + assert Path(fname).exists() + Path(fname).unlink() def test_psconvert_twice(): @@ -33,13 +33,13 @@ def test_psconvert_twice(): # Make a PDF fig.psconvert(prefix=prefix, fmt="f") fname = prefix + ".pdf" - assert os.path.exists(fname) - os.remove(fname) + assert Path(fname).exists() + Path(fname).unlink() # Make a PNG fig.psconvert(prefix=prefix, fmt="g") fname = prefix + ".png" - assert os.path.exists(fname) - os.remove(fname) + assert Path(fname).exists() + Path(fname).unlink() def test_psconvert_without_prefix(): diff --git a/pygmt/tests/test_session_management.py b/pygmt/tests/test_session_management.py index 0fbe6f8e45b..77a3970787f 100644 --- a/pygmt/tests/test_session_management.py +++ b/pygmt/tests/test_session_management.py @@ -3,7 +3,6 @@ """ import multiprocessing as mp -import os from importlib import reload from pathlib import Path @@ -25,8 +24,8 @@ def test_begin_end(): lib.call_module("basemap", "-R10/70/-3/8 -JX4i/3i -Ba") end() begin() # Restart the global session - assert os.path.exists("pygmt-session.pdf") - os.remove("pygmt-session.pdf") + assert Path("pygmt-session.pdf").exists() + Path("pygmt-session.pdf").unlink() def test_gmt_compat_6_is_applied(capsys): @@ -54,12 +53,12 @@ def test_gmt_compat_6_is_applied(capsys): finally: end() # Clean up the global "gmt.conf" in the current directory - assert os.path.exists("gmt.conf") - os.remove("gmt.conf") - assert os.path.exists("pygmt-session.pdf") - os.remove("pygmt-session.pdf") + assert Path("gmt.conf").exists() + Path("gmt.conf").unlink() + assert Path("pygmt-session.pdf").exists() + Path("pygmt-session.pdf").unlink() # Make sure no global "gmt.conf" in the current directory - assert not os.path.exists("gmt.conf") + assert not Path("gmt.conf").exists() begin() # Restart the global session diff --git a/pygmt/tests/test_sphinx_gallery.py b/pygmt/tests/test_sphinx_gallery.py index 205f0f3e3e5..eb8ed135d0a 100644 --- a/pygmt/tests/test_sphinx_gallery.py +++ b/pygmt/tests/test_sphinx_gallery.py @@ -3,6 +3,7 @@ """ import os +from pathlib import Path from tempfile import TemporaryDirectory import pytest @@ -31,9 +32,9 @@ def test_pygmtscraper(): conf = {"src_dir": "meh"} fname = os.path.join(tmpdir, "meh.png") block_vars = {"image_path_iterator": (i for i in [fname])} - assert not os.path.exists(fname) + assert not Path(fname).exists() scraper(None, block_vars, conf) - assert os.path.exists(fname) + assert Path(fname).exists() assert not SHOWED_FIGURES finally: SHOWED_FIGURES.extend(showed) diff --git a/pygmt/tests/test_x2sys_cross.py b/pygmt/tests/test_x2sys_cross.py index 226fbc06e6d..04cc4e4dabe 100644 --- a/pygmt/tests/test_x2sys_cross.py +++ b/pygmt/tests/test_x2sys_cross.py @@ -188,7 +188,7 @@ def test_x2sys_cross_input_two_filenames(): columns = list(output.columns) assert columns[:6] == ["x", "y", "i_1", "i_2", "dist_1", "dist_2"] assert columns[6:] == ["head_1", "head_2", "vel_1", "vel_2", "z_X", "z_M"] - _ = [os.remove(f"track_{i}.xyz") for i in range(2)] # cleanup track files + _ = [Path(f"track_{i}.xyz").unlink() for i in range(2)] # cleanup track files def test_x2sys_cross_invalid_tracks_input_type(tracks):