Skip to content

Commit 0cdb87d

Browse files
authored
Migrate from os.path to pathlib (#3119)
1 parent bfb641e commit 0cdb87d

26 files changed

+131
-149
lines changed

examples/gallery/images/image.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
"""
1212

1313
# %%
14-
import os
14+
from pathlib import Path
1515

1616
import pygmt
1717

@@ -28,6 +28,6 @@
2828
)
2929

3030
# clean up the downloaded image in the current directory
31-
os.remove("gmt-logo.png")
31+
Path("gmt-logo.png").unlink()
3232

3333
fig.show()

examples/tutorials/basics/text.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
"""
88

99
# %%
10-
import os
10+
from pathlib import Path
1111

1212
import pygmt
1313

@@ -88,7 +88,7 @@
8888
fig.text(textfiles="examples.txt", angle=True, font=True, justify=True)
8989

9090
# Cleanups
91-
os.remove("examples.txt")
91+
Path("examples.txt").unlink()
9292

9393
fig.show()
9494

pygmt/figure.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,9 @@ class Figure:
6767
>>> fig.basemap(region=[0, 360, -90, 90], projection="W15c", frame=True)
6868
>>> fig.savefig("my-figure.png")
6969
>>> # Make sure the figure file is generated and clean it up
70-
>>> import os
71-
>>> os.path.exists("my-figure.png")
72-
True
73-
>>> os.remove("my-figure.png")
70+
>>> from pathlib import Path
71+
>>> assert Path("my-figure.png").exists()
72+
>>> Path("my-figure.png").unlink()
7473
7574
The plot region can be specified through ISO country codes (for example,
7675
``"JP"`` for Japan):
@@ -380,8 +379,8 @@ def savefig( # noqa: PLR0912
380379
# Remove the .pgw world file if exists
381380
# Not necessary after GMT 6.5.0.
382381
# See upstream fix https://github.com/GenericMappingTools/gmt/pull/7865
383-
if ext == "tiff" and fname.with_suffix(".pgw").exists():
384-
fname.with_suffix(".pgw").unlink()
382+
if ext == "tiff":
383+
fname.with_suffix(".pgw").unlink(missing_ok=True)
385384

386385
# Rename if file extension doesn't match the input file suffix
387386
if ext != suffix[1:]:
@@ -495,7 +494,7 @@ def _preview(self, fmt, dpi, as_bytes=False, **kwargs):
495494
If ``as_bytes=False``, this is the file name of the preview image
496495
file. Else, it is the file content loaded as a bytes string.
497496
"""
498-
fname = os.path.join(self._preview_dir.name, f"{self._name}.{fmt}")
497+
fname = Path(self._preview_dir.name) / f"{self._name}.{fmt}"
499498
self.savefig(fname, dpi=dpi, **kwargs)
500499
if as_bytes:
501500
with open(fname, "rb") as image:

pygmt/helpers/tempfile.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
Utilities for dealing with temporary file management.
33
"""
44

5-
import os
65
import uuid
76
from contextlib import contextmanager
7+
from pathlib import Path
88
from tempfile import NamedTemporaryFile
99

1010
import numpy as np
@@ -72,8 +72,7 @@ def __exit__(self, *args):
7272
"""
7373
Remove the temporary file.
7474
"""
75-
if os.path.exists(self.name):
76-
os.remove(self.name)
75+
Path(self.name).unlink(missing_ok=True)
7776

7877
def read(self, keep_tabs=False):
7978
"""
@@ -133,7 +132,7 @@ def tempfile_from_geojson(geojson):
133132
with GMTTempFile(suffix=".gmt") as tmpfile:
134133
import geopandas as gpd
135134

136-
os.remove(tmpfile.name) # ensure file is deleted first
135+
Path(tmpfile.name).unlink() # Ensure file is deleted first
137136
ogrgmt_kwargs = {"filename": tmpfile.name, "driver": "OGR_GMT", "mode": "w"}
138137
try:
139138
# OGR_GMT only supports 32-bit integers. We need to map int/int64
@@ -185,7 +184,7 @@ def tempfile_from_image(image):
185184
A temporary GeoTIFF file holding the image data. E.g. '1a2b3c4d5.tif'.
186185
"""
187186
with GMTTempFile(suffix=".tif") as tmpfile:
188-
os.remove(tmpfile.name) # ensure file is deleted first
187+
Path(tmpfile.name).unlink() # Ensure file is deleted first
189188
try:
190189
image.rio.to_raster(raster_path=tmpfile.name)
191190
except AttributeError as e: # object has no attribute 'rio'

pygmt/helpers/testing.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44

55
import importlib
66
import inspect
7-
import os
87
import string
8+
from pathlib import Path
99

1010
from pygmt.exceptions import GMTImageComparisonFailure
1111
from pygmt.io import load_dataarray
@@ -39,6 +39,7 @@ def check_figures_equal(*, extensions=("png",), tol=0.0, result_dir="result_imag
3939
>>> import pytest
4040
>>> import shutil
4141
>>> from pygmt import Figure
42+
>>> from pathlib import Path
4243
4344
>>> @check_figures_equal(result_dir="tmp_result_images")
4445
... def test_check_figures_equal():
@@ -50,7 +51,7 @@ def check_figures_equal(*, extensions=("png",), tol=0.0, result_dir="result_imag
5051
... )
5152
... return fig_ref, fig_test
5253
>>> test_check_figures_equal()
53-
>>> assert len(os.listdir("tmp_result_images")) == 0
54+
>>> assert len(list(Path("tmp_result_images").iterdir())) == 0
5455
>>> shutil.rmtree(path="tmp_result_images") # cleanup folder if tests pass
5556
5657
>>> @check_figures_equal(result_dir="tmp_result_images")
@@ -63,12 +64,9 @@ def check_figures_equal(*, extensions=("png",), tol=0.0, result_dir="result_imag
6364
>>> with pytest.raises(GMTImageComparisonFailure):
6465
... test_check_figures_unequal()
6566
>>> for suffix in ["", "-expected", "-failed-diff"]:
66-
... assert os.path.exists(
67-
... os.path.join(
68-
... "tmp_result_images",
69-
... f"test_check_figures_unequal{suffix}.png",
70-
... )
71-
... )
67+
... assert (
68+
... Path("tmp_result_images") / f"test_check_figures_unequal{suffix}.png"
69+
... ).exists()
7270
>>> shutil.rmtree(path="tmp_result_images") # cleanup folder if tests pass
7371
"""
7472
allowed_chars = set(string.digits + string.ascii_letters + "_-[]()")
@@ -78,7 +76,7 @@ def decorator(func):
7876
import pytest
7977
from matplotlib.testing.compare import compare_images
8078

81-
os.makedirs(result_dir, exist_ok=True)
79+
Path(result_dir).mkdir(parents=True, exist_ok=True)
8280
old_sig = inspect.signature(func)
8381

8482
@pytest.mark.parametrize("ext", extensions)
@@ -93,8 +91,8 @@ def wrapper(*args, ext="png", request=None, **kwargs):
9391
file_name = func.__name__
9492
try:
9593
fig_ref, fig_test = func(*args, **kwargs)
96-
ref_image_path = os.path.join(result_dir, f"{file_name}-expected.{ext}")
97-
test_image_path = os.path.join(result_dir, f"{file_name}.{ext}")
94+
ref_image_path = Path(result_dir) / f"{file_name}-expected.{ext}"
95+
test_image_path = Path(result_dir) / f"{file_name}.{ext}"
9896
fig_ref.savefig(ref_image_path)
9997
fig_test.savefig(test_image_path)
10098

@@ -107,11 +105,11 @@ def wrapper(*args, ext="png", request=None, **kwargs):
107105
in_decorator=True,
108106
)
109107
if err is None: # Images are the same
110-
os.remove(ref_image_path)
111-
os.remove(test_image_path)
108+
ref_image_path.unlink()
109+
test_image_path.unlink()
112110
else: # Images are not the same
113111
for key in ["actual", "expected", "diff"]:
114-
err[key] = os.path.relpath(err[key])
112+
err[key] = Path(err[key]).relative_to(".")
115113
raise GMTImageComparisonFailure(
116114
f"images not close (RMS {err['rms']:.3f}):\n"
117115
f"\t{err['actual']}\n"

pygmt/src/grdfilter.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def grdfilter(grid, **kwargs):
114114
115115
Examples
116116
--------
117-
>>> import os
117+
>>> from pathlib import Path
118118
>>> import pygmt
119119
>>> # Apply a filter of 600 km (full width) to the @earth_relief_30m_g file
120120
>>> # and return a filtered field (saved as netCDF)
@@ -126,7 +126,7 @@ def grdfilter(grid, **kwargs):
126126
... spacing=0.5,
127127
... outgrid="filtered_pacific.nc",
128128
... )
129-
>>> os.remove("filtered_pacific.nc") # Cleanup file
129+
>>> Path("filtered_pacific.nc").unlink() # Cleanup file
130130
>>> # Apply a Gaussian smoothing filter of 600 km to the input DataArray
131131
>>> # and return a filtered DataArray with the smoothed field
132132
>>> grid = pygmt.datasets.load_earth_relief()

pygmt/src/x2sys_cross.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def tempfile_from_dftrack(track, suffix):
5353
)
5454
yield tmpfilename
5555
finally:
56-
os.remove(tmpfilename)
56+
Path(tmpfilename).unlink()
5757

5858

5959
@fmt_docstring

pygmt/tests/test_accessor.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
Test the behaviour of the GMTDataArrayAccessor class.
33
"""
44

5-
import os
65
import sys
76
from pathlib import Path
87

@@ -101,7 +100,7 @@ def test_accessor_sliced_datacube():
101100
assert grid.gmt.registration == 0 # gridline registration
102101
assert grid.gmt.gtype == 1 # geographic coordinate type
103102
finally:
104-
os.remove(fname)
103+
Path(fname).unlink()
105104

106105

107106
def test_accessor_grid_source_file_not_exist():

pygmt/tests/test_clib.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
Test the wrappers for the C API.
33
"""
44

5-
import os
65
from contextlib import contextmanager
76
from pathlib import Path
87

@@ -22,7 +21,7 @@
2221
)
2322
from pygmt.helpers import GMTTempFile
2423

25-
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
24+
POINTS_DATA = Path(__file__).parent / "data" / "points.txt"
2625

2726

2827
@contextmanager
@@ -136,11 +135,10 @@ def test_call_module():
136135
"""
137136
Run a command to see if call_module works.
138137
"""
139-
data_fname = os.path.join(TEST_DATA_DIR, "points.txt")
140138
out_fname = "test_call_module.txt"
141139
with clib.Session() as lib:
142140
with GMTTempFile() as out_fname:
143-
lib.call_module("info", f"{data_fname} -C ->{out_fname.name}")
141+
lib.call_module("info", f"{POINTS_DATA} -C ->{out_fname.name}")
144142
assert Path(out_fname.name).stat().st_size > 0
145143
output = out_fname.read().strip()
146144
assert output == "11.5309 61.7074 -2.9289 7.8648 0.1412 0.9338"

pygmt/tests/test_clib_virtualfiles.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
Test the C API functions related to virtual files.
33
"""
44

5-
import os
65
from importlib.util import find_spec
76
from itertools import product
7+
from pathlib import Path
88

99
import numpy as np
1010
import pandas as pd
@@ -15,8 +15,7 @@
1515
from pygmt.helpers import GMTTempFile
1616
from pygmt.tests.test_clib import mock
1717

18-
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
19-
POINTS_DATA = os.path.join(TEST_DATA_DIR, "points.txt")
18+
POINTS_DATA = Path(__file__).parent / "data" / "points.txt"
2019

2120

2221
@pytest.fixture(scope="module", name="data")

0 commit comments

Comments
 (0)