Skip to content

Commit

Permalink
Migrate from os.path to pathlib
Browse files Browse the repository at this point in the history
  • Loading branch information
seisman committed Mar 18, 2024
1 parent bcbbcad commit dc4acc5
Show file tree
Hide file tree
Showing 14 changed files with 45 additions and 47 deletions.
4 changes: 2 additions & 2 deletions examples/gallery/images/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"""

# %%
import os
from pathlib import Path

import pygmt

Expand All @@ -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()
4 changes: 2 additions & 2 deletions examples/tutorials/basics/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"""

# %%
import os
from pathlib import Path

import pygmt

Expand Down Expand Up @@ -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()

Expand Down
6 changes: 3 additions & 3 deletions pygmt/figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
9 changes: 4 additions & 5 deletions pygmt/helpers/tempfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
"""
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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'
Expand Down
15 changes: 7 additions & 8 deletions pygmt/helpers/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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():
Expand All @@ -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 + "_-[]()")
Expand Down Expand Up @@ -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])
Expand Down
4 changes: 2 additions & 2 deletions pygmt/src/grdfilter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion pygmt/src/x2sys_cross.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def tempfile_from_dftrack(track, suffix):
)
yield tmpfilename
finally:
os.remove(tmpfilename)
Path(tmpfilename).unlink()


@fmt_docstring
Expand Down
3 changes: 1 addition & 2 deletions pygmt/tests/test_accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
Test the behaviour of the GMTDataArrayAccessor class.
"""

import os
import sys
from pathlib import Path

Expand Down Expand Up @@ -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():
Expand Down
4 changes: 2 additions & 2 deletions pygmt/tests/test_figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
5 changes: 3 additions & 2 deletions pygmt/tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""

import os
from pathlib import Path

import numpy as np
import pytest
Expand Down Expand Up @@ -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():
Expand Down
14 changes: 7 additions & 7 deletions pygmt/tests/test_psconvert.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
Test Figure.psconvert.
"""

import os
from pathlib import Path

import pytest
from pygmt import Figure
Expand All @@ -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():
Expand All @@ -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():
Expand Down
15 changes: 7 additions & 8 deletions pygmt/tests/test_session_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
"""

import multiprocessing as mp
import os
from importlib import reload
from pathlib import Path

Expand All @@ -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):
Expand Down Expand Up @@ -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


Expand Down
5 changes: 3 additions & 2 deletions pygmt/tests/test_sphinx_gallery.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""

import os
from pathlib import Path
from tempfile import TemporaryDirectory

import pytest
Expand Down Expand Up @@ -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)
2 changes: 1 addition & 1 deletion pygmt/tests/test_x2sys_cross.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down

0 comments on commit dc4acc5

Please sign in to comment.