diff --git a/examples/tutorials/basics/text.py b/examples/tutorials/basics/text.py index 1f225bb39c3..43bd76ed799 100644 --- a/examples/tutorials/basics/text.py +++ b/examples/tutorials/basics/text.py @@ -72,7 +72,7 @@ fig.coast(land="black", water="skyblue") # Create space-delimited file -with open("examples.txt", "w") as f: +with Path("examples.txt").open(mode="w") as f: f.write("114 0.5 0 22p,Helvetica-Bold,white CM BORNEO\n") f.write("119 3.25 0 12p,Helvetica-Bold,black CM CELEBES SEA\n") f.write("112 -4.6 0 12p,Helvetica-Bold,black CM JAVA SEA\n") diff --git a/pygmt/clib/session.py b/pygmt/clib/session.py index 6e6e495e244..1bea0e4b886 100644 --- a/pygmt/clib/session.py +++ b/pygmt/clib/session.py @@ -1641,12 +1641,13 @@ def virtualfile_out( Examples -------- + >>> from pathlib import Path >>> from pygmt.clib import Session >>> from pygmt.datatypes import _GMT_DATASET >>> from pygmt.helpers import GMTTempFile >>> >>> with GMTTempFile(suffix=".txt") as tmpfile: - ... with open(tmpfile.name, mode="w") as fp: + ... with Path(tmpfile.name).open(mode="w") as fp: ... print("1.0 2.0 3.0 TEXT", file=fp) ... ... # Create a virtual file for storing the output table. @@ -1661,8 +1662,7 @@ def virtualfile_out( ... with lib.virtualfile_out(fname=tmpfile.name) as vouttbl: ... assert vouttbl == tmpfile.name ... lib.call_module("read", f"{tmpfile.name} {vouttbl} -Td") - ... with open(vouttbl, mode="r") as fp: - ... line = fp.readline() + ... line = Path(vouttbl).read_text() ... assert line == "1\t2\t3\tTEXT\n" """ if fname is not None: # Yield the actual file name. @@ -1692,13 +1692,14 @@ def read_virtualfile( Examples -------- + >>> from pathlib import Path >>> from pygmt.clib import Session >>> from pygmt.helpers import GMTTempFile >>> >>> # Read dataset from a virtual file >>> with Session() as lib: ... with GMTTempFile(suffix=".txt") as tmpfile: - ... with open(tmpfile.name, mode="w") as fp: + ... with Path(tmpfile.name).open(mode="w") as fp: ... print("1.0 2.0 3.0 TEXT", file=fp) ... with lib.virtualfile_out(kind="dataset") as vouttbl: ... lib.call_module("read", f"{tmpfile.name} {vouttbl} -Td") @@ -1779,7 +1780,7 @@ def virtualfile_to_dataset( >>> >>> with GMTTempFile(suffix=".txt") as tmpfile: ... # prepare the sample data file - ... with open(tmpfile.name, mode="w") as fp: + ... with Path(tmpfile.name).open(mode="w") as fp: ... print(">", file=fp) ... print("1.0 2.0 3.0 TEXT1 TEXT23", file=fp) ... print("4.0 5.0 6.0 TEXT4 TEXT567", file=fp) diff --git a/pygmt/datatypes/dataset.py b/pygmt/datatypes/dataset.py index 21953ee9051..a0d0547f3ca 100644 --- a/pygmt/datatypes/dataset.py +++ b/pygmt/datatypes/dataset.py @@ -18,12 +18,13 @@ class _GMT_DATASET(ctp.Structure): # noqa: N801 Examples -------- + >>> from pathlib import Path >>> from pygmt.helpers import GMTTempFile >>> from pygmt.clib import Session >>> >>> with GMTTempFile(suffix=".txt") as tmpfile: ... # Prepare the sample data file - ... with open(tmpfile.name, mode="w") as fp: + ... with Path(tmpfile.name).open(mode="w") as fp: ... print(">", file=fp) ... print("1.0 2.0 3.0 TEXT1 TEXT23", file=fp) ... print("4.0 5.0 6.0 TEXT4 TEXT567", file=fp) @@ -157,12 +158,13 @@ def to_dataframe(self) -> pd.DataFrame: Examples -------- + >>> from pathlib import Path >>> from pygmt.helpers import GMTTempFile >>> from pygmt.clib import Session >>> >>> with GMTTempFile(suffix=".txt") as tmpfile: ... # prepare the sample data file - ... with open(tmpfile.name, mode="w") as fp: + ... with Path(tmpfile.name).open(mode="w") as fp: ... print(">", file=fp) ... print("1.0 2.0 3.0 TEXT1 TEXT23", file=fp) ... print("4.0 5.0 6.0 TEXT4 TEXT567", file=fp) diff --git a/pygmt/figure.py b/pygmt/figure.py index f908cff1b93..ebeccc90287 100644 --- a/pygmt/figure.py +++ b/pygmt/figure.py @@ -497,9 +497,7 @@ def _preview(self, fmt, dpi, as_bytes=False, **kwargs): fname = Path(self._preview_dir.name) / f"{self._name}.{fmt}" self.savefig(fname, dpi=dpi, **kwargs) if as_bytes: - with open(fname, "rb") as image: - preview = image.read() - return preview + return fname.read_bytes() return fname def _repr_png_(self): diff --git a/pygmt/helpers/tempfile.py b/pygmt/helpers/tempfile.py index bed79f352ae..3cbb88060df 100644 --- a/pygmt/helpers/tempfile.py +++ b/pygmt/helpers/tempfile.py @@ -88,11 +88,10 @@ def read(self, keep_tabs=False): content : str Content of the temporary file as a Unicode string. """ - with open(self.name, encoding="utf8") as tmpfile: - content = tmpfile.read() - if not keep_tabs: - content = content.replace("\t", " ") - return content + content = Path(self.name).read_text(encoding="utf8") + if not keep_tabs: + content = content.replace("\t", " ") + return content def loadtxt(self, **kwargs): """ diff --git a/pygmt/src/plot.py b/pygmt/src/plot.py index b4c01b9438e..0ed42569386 100644 --- a/pygmt/src/plot.py +++ b/pygmt/src/plot.py @@ -2,6 +2,8 @@ plot - Plot in two dimensions. """ +from pathlib import Path + from pygmt.clib import Session from pygmt.exceptions import GMTInvalidInput from pygmt.helpers import ( @@ -220,7 +222,7 @@ def plot( # noqa: PLR0912 elif kwargs.get("S") is None and kind == "file" and str(data).endswith(".gmt"): # checking that the data is a file path to set default style try: - with open(which(data), encoding="utf8") as file: + with Path(which(data)).open(encoding="utf8") as file: line = file.readline() if "@GMULTIPOINT" in line or "@GPOINT" in line: # if the file is gmt style and geometry is set to Point diff --git a/pygmt/src/plot3d.py b/pygmt/src/plot3d.py index 029820bcec4..71407a65c90 100644 --- a/pygmt/src/plot3d.py +++ b/pygmt/src/plot3d.py @@ -2,6 +2,8 @@ plot3d - Plot in three dimensions. """ +from pathlib import Path + from pygmt.clib import Session from pygmt.exceptions import GMTInvalidInput from pygmt.helpers import ( @@ -195,7 +197,7 @@ def plot3d( # noqa: PLR0912 elif kwargs.get("S") is None and kind == "file" and str(data).endswith(".gmt"): # checking that the data is a file path to set default style try: - with open(which(data), encoding="utf8") as file: + with Path(which(data)).open(encoding="utf8") as file: line = file.readline() if "@GMULTIPOINT" in line or "@GPOINT" in line: # if the file is gmt style and geometry is set to Point diff --git a/pygmt/tests/test_helpers.py b/pygmt/tests/test_helpers.py index 9b25c71aa0b..b805523f75d 100644 --- a/pygmt/tests/test_helpers.py +++ b/pygmt/tests/test_helpers.py @@ -132,8 +132,7 @@ def test_gmttempfile_read(): Make sure GMTTempFile.read() works. """ with GMTTempFile() as tmpfile: - with open(tmpfile.name, "w", encoding="utf8") as ftmp: - ftmp.write("in.dat: N = 2\t<1/3>\t<2/4>\n") + Path(tmpfile.name).write_text("in.dat: N = 2\t<1/3>\t<2/4>\n") assert tmpfile.read() == "in.dat: N = 2 <1/3> <2/4>\n" assert tmpfile.read(keep_tabs=True) == "in.dat: N = 2\t<1/3>\t<2/4>\n" diff --git a/pygmt/tests/test_legend.py b/pygmt/tests/test_legend.py index 9c4936d9984..8721bb66384 100644 --- a/pygmt/tests/test_legend.py +++ b/pygmt/tests/test_legend.py @@ -2,6 +2,8 @@ Test Figure.legend. """ +from pathlib import Path + import pytest from pygmt import Figure from pygmt.exceptions import GMTInvalidInput @@ -95,8 +97,7 @@ def test_legend_specfile(): """ with GMTTempFile() as specfile: - with open(specfile.name, "w", encoding="utf8") as file: - file.write(specfile_contents) + Path(specfile.name).write_text(specfile_contents) fig = Figure() fig.basemap(projection="x6i", region=[0, 1, 0, 1], frame=True) fig.legend(specfile.name, position="JTM+jCM+w5i") diff --git a/pygmt/tests/test_meca.py b/pygmt/tests/test_meca.py index bcf69f059f3..e54799711ad 100644 --- a/pygmt/tests/test_meca.py +++ b/pygmt/tests/test_meca.py @@ -2,6 +2,8 @@ Test Figure.meca. """ +from pathlib import Path + import numpy as np import pandas as pd import pytest @@ -72,13 +74,8 @@ def test_meca_spec_single_focalmecha_file(): fig = Figure() fig.basemap(region=[-1, 1, 4, 6], projection="M8c", frame=2) with GMTTempFile() as temp: - with open(temp.name, mode="w", encoding="utf8") as temp_file: - temp_file.write("0 5 0 0 90 0 5") - fig.meca( - spec=temp.name, - convention="aki", - scale="2.5c", - ) + Path(temp.name).write_text("0 5 0 0 90 0 5") + fig.meca(spec=temp.name, convention="aki", scale="2.5c") return fig diff --git a/pygmt/tests/test_plot.py b/pygmt/tests/test_plot.py index 76158bfe038..ecae491c6fa 100644 --- a/pygmt/tests/test_plot.py +++ b/pygmt/tests/test_plot.py @@ -487,8 +487,7 @@ def test_plot_ogrgmt_file_multipoint_default_style(func): # FEATURE_DATA 1 2 """ - with open(tmpfile.name, "w", encoding="utf8") as file: - file.write(gmt_file) + Path(tmpfile.name).write_text(gmt_file) fig = Figure() fig.plot( data=func(tmpfile.name), region=[0, 2, 1, 3], projection="X2c", frame=True @@ -507,8 +506,7 @@ def test_plot_ogrgmt_file_multipoint_non_default_style(): # FEATURE_DATA 1 2 """ - with open(tmpfile.name, "w", encoding="utf8") as file: - file.write(gmt_file) + Path(tmpfile.name).write_text(gmt_file) fig = Figure() fig.plot( data=tmpfile.name, diff --git a/pygmt/tests/test_plot3d.py b/pygmt/tests/test_plot3d.py index c37c899a30b..33f3c94812f 100644 --- a/pygmt/tests/test_plot3d.py +++ b/pygmt/tests/test_plot3d.py @@ -444,8 +444,7 @@ def test_plot3d_ogrgmt_file_multipoint_default_style(func): > 1 1 2 1.5 1.5 1""" - with open(tmpfile.name, "w", encoding="utf8") as file: - file.write(gmt_file) + Path(tmpfile.name).write_text(gmt_file) fig = Figure() fig.plot3d( data=func(tmpfile.name), @@ -470,8 +469,7 @@ def test_plot3d_ogrgmt_file_multipoint_non_default_style(): > 1 1 2 1.5 1.5 1""" - with open(tmpfile.name, "w", encoding="utf8") as file: - file.write(gmt_file) + Path(tmpfile.name).write_text(gmt_file) fig = Figure() fig.plot3d( data=tmpfile.name, diff --git a/pygmt/tests/test_text.py b/pygmt/tests/test_text.py index 3969c451e68..1ef6a19bc11 100644 --- a/pygmt/tests/test_text.py +++ b/pygmt/tests/test_text.py @@ -299,8 +299,7 @@ def test_text_angle_font_justify_from_textfile(): """ fig = Figure() with GMTTempFile(suffix=".txt") as tempfile: - with open(tempfile.name, "w", encoding="utf8") as tmpfile: - tmpfile.write("114 0.5 30 22p,Helvetica-Bold,black LM BORNEO") + Path(tempfile.name).write_text("114 0.5 30 22p,Helvetica-Bold,black LM BORNEO") fig.text( region=[113, 117.5, -0.5, 3], projection="M5c", diff --git a/pygmt/tests/test_x2sys_cross.py b/pygmt/tests/test_x2sys_cross.py index 49256953707..c9209bd254a 100644 --- a/pygmt/tests/test_x2sys_cross.py +++ b/pygmt/tests/test_x2sys_cross.py @@ -24,7 +24,7 @@ def _fixture_mock_x2sys_home(monkeypatch): Set the X2SYS_HOME environment variable to the current working directory for the test session. """ - monkeypatch.setenv("X2SYS_HOME", Path.cwd()) + monkeypatch.setenv("X2SYS_HOME", str(Path.cwd())) @pytest.fixture(scope="module", name="tracks") @@ -115,7 +115,7 @@ def test_x2sys_cross_input_two_dataframes(): ) # Add a time row to the x2sys fmtfile - with open(tmpdir_p / "xyz.fmt", mode="a", encoding="utf8") as fmtfile: + with (tmpdir_p / "xyz.fmt").open(mode="a", encoding="utf8") as fmtfile: fmtfile.write("time\ta\tN\t0\t1\t0\t%g\n") # Create pandas.DataFrame track tables @@ -175,10 +175,7 @@ def test_x2sys_cross_input_two_filenames(): # Create temporary xyz files for i in range(2): rng = np.random.default_rng(seed=i) - with open( - Path.cwd() / f"track_{i}.xyz", mode="w", encoding="utf8" - ) as fname: - np.savetxt(fname=fname, X=rng.random((10, 3))) + np.savetxt(fname=Path.cwd() / f"track_{i}.xyz", X=rng.random((10, 3))) output = x2sys_cross(tracks=["track_0.xyz", "track_1.xyz"], tag=tag, coe="e") diff --git a/pygmt/tests/test_x2sys_init.py b/pygmt/tests/test_x2sys_init.py index c0664110eda..70b1b8bc57c 100644 --- a/pygmt/tests/test_x2sys_init.py +++ b/pygmt/tests/test_x2sys_init.py @@ -15,7 +15,7 @@ def _fixture_mock_x2sys_home(monkeypatch): Set the X2SYS_HOME environment variable to the current working directory for the test session. """ - monkeypatch.setenv("X2SYS_HOME", Path.cwd()) + monkeypatch.setenv("X2SYS_HOME", str(Path.cwd())) @pytest.mark.usefixtures("mock_x2sys_home") @@ -30,11 +30,9 @@ def test_x2sys_init_region_spacing(): x2sys_init( tag=tag, fmtfile="xyz", force=True, region=[0, 10, 20, 30], spacing=[5, 5] ) - - with open(tmpdir_p / f"{tag}.tag", encoding="utf8") as tagpath: - tail_line = tagpath.readlines()[-1] - assert "-R0/10/20/30" in tail_line - assert "-I5/5" in tail_line + tail_line = (tmpdir_p / f"{tag}.tag").read_text().splitlines()[-1] + assert "-R0/10/20/30" in tail_line + assert "-I5/5" in tail_line @pytest.mark.benchmark @@ -54,7 +52,6 @@ def test_x2sys_init_units_gap(): gap=["tseconds", "de"], ) - with open(tmpdir_p / f"{tag}.tag", encoding="utf8") as tagpath: - tail_line = tagpath.readlines()[-1] - assert "-Nse -Nde" in tail_line - assert "-Wtseconds -Wde" in tail_line + tail_line = (tmpdir_p / f"{tag}.tag").read_text().splitlines()[-1] + assert "-Nse -Nde" in tail_line + assert "-Wtseconds -Wde" in tail_line diff --git a/pyproject.toml b/pyproject.toml index 0ae8a526d52..27637b2f6a9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -107,6 +107,7 @@ select = [ "PIE", # flake8-pie "PL", # pylint "PT", # flake8-pytest-style + "PTH", # flake8-use-pathlib "RET", # flake8-return "RSE", # flake8-raise "RUF", # ruff-specific