diff --git a/display/d.mon/render_cmd.py b/display/d.mon/render_cmd.py index 2959440897e..7f1d2d54dbc 100644 --- a/display/d.mon/render_cmd.py +++ b/display/d.mon/render_cmd.py @@ -73,7 +73,7 @@ def render(cmd, mapfile): grass.run_command(cmd[0], env=env, **cmd[1]) # display driver can generate a blank map file unnecessarily for # non-rendering modules; delete it - if cmd[0] in non_rendering_modules and os.path.exists(mapfile): + if cmd[0] in non_rendering_modules and Path(mapfile).exists(): remove_mapfile(mapfile) except CalledModuleError as e: @@ -198,7 +198,7 @@ def read_stdin(cmd): render(cmd, mapfile) update_cmd_file(os.path.join(path, "cmd"), cmd, mapfile) - if cmd[0] == "d.erase" and os.path.exists(legfile): + if cmd[0] == "d.erase" and Path(legfile).exists(): os.remove(legfile) sys.exit(0) diff --git a/gui/wxpython/animation/data.py b/gui/wxpython/animation/data.py index 810aafc0587..0d828a8b3c7 100644 --- a/gui/wxpython/animation/data.py +++ b/gui/wxpython/animation/data.py @@ -16,8 +16,8 @@ @author Anna Petrasova """ -import os import copy +from pathlib import Path from grass.script.utils import parse_key_val from grass.script import core as gcore @@ -134,7 +134,7 @@ def SetWorkspaceFile(self, fileName): if fileName == "": raise ValueError(_("No workspace file selected.")) - if not os.path.exists(fileName): + if not Path(fileName).exists(): raise OSError(_("File %s not found") % fileName) self._workspaceFile = fileName diff --git a/gui/wxpython/animation/dialogs.py b/gui/wxpython/animation/dialogs.py index d64eed093d4..d3aef590d99 100644 --- a/gui/wxpython/animation/dialogs.py +++ b/gui/wxpython/animation/dialogs.py @@ -1443,7 +1443,7 @@ def OnRemove(self, event): def OnExport(self, event): for decor in self.decorations: if decor["name"] == "image": - if not os.path.exists(decor["file"]): + if not Path(decor["file"]).exists(): if decor["file"]: GError( parent=self, message=_("File %s not found.") % decor["file"] @@ -1456,7 +1456,7 @@ def OnExport(self, event): if self.formatChoice.GetSelection() == 0: name = self.dirBrowse.GetValue() - if not os.path.exists(name): + if not Path(name).exists(): if name: GError(parent=self, message=_("Directory %s not found.") % name) else: @@ -1553,7 +1553,7 @@ def _export_file_validation(self, filebrowsebtn, file_path, file_postfix): file_path += file_postfix base_dir = os.path.dirname(file_path) - if not os.path.exists(base_dir): + if not Path(base_dir).exists(): GError( parent=self, message=file_path_does_not_exist_err_message.format( @@ -1562,7 +1562,7 @@ def _export_file_validation(self, filebrowsebtn, file_path, file_postfix): ) return False - if os.path.exists(file_path): + if Path(file_path).exists(): overwrite_dlg = wx.MessageDialog( self.GetParent(), message=_( diff --git a/gui/wxpython/animation/provider.py b/gui/wxpython/animation/provider.py index e10f75cede6..563654d3535 100644 --- a/gui/wxpython/animation/provider.py +++ b/gui/wxpython/animation/provider.py @@ -25,6 +25,7 @@ import wx import tempfile from multiprocessing import Process, Queue +from pathlib import Path from core.gcmd import GException, DecodeString from core.settings import UserSettings @@ -175,7 +176,7 @@ def _dryRender(self, uniqueCmds, regions, force): filename = GetFileFromCmd(self._tempDir, cmd, region) if ( not force - and os.path.exists(filename) + and Path(filename).exists() and self._mapFilesPool.GetSize(HashCmd(cmd, region)) == (self.imageWidth, self.imageHeight) ): @@ -378,7 +379,7 @@ def Render(self, cmdList, regions, regionFor3D, bgcolor, force, nprocs): filename = GetFileFromCmd(self._tempDir, cmd, region) if ( not force - and os.path.exists(filename) + and Path(filename).exists() and self._mapFilesPool.GetSize(HashCmd(cmd, region)) == (self.imageWidth, self.imageHeight) ): @@ -791,7 +792,7 @@ def __init__(self, tempDir): def __call__(self): import shutil - if os.path.exists(self._tempDir): + if Path(self._tempDir).exists(): try: shutil.rmtree(self._tempDir) Debug.msg(5, "CleanUp: removed directory {t}".format(t=self._tempDir)) @@ -901,7 +902,7 @@ def test(): mapFilesPool = MapFilesPool() tempDir = "/tmp/test" - if os.path.exists(tempDir): + if Path(tempDir).exists(): shutil.rmtree(tempDir) os.mkdir(tempDir) # comment this line to keep the directory after program ends diff --git a/gui/wxpython/core/gconsole.py b/gui/wxpython/core/gconsole.py index 29565695339..26a46e8b54a 100644 --- a/gui/wxpython/core/gconsole.py +++ b/gui/wxpython/core/gconsole.py @@ -31,6 +31,7 @@ import codecs import locale +from pathlib import Path import wx from wx.lib.newevent import NewEvent @@ -607,11 +608,11 @@ def load_source(modname, filename): if sys.platform == "win32": pyFile += ".py" pyPath = os.path.join(os.environ["GISBASE"], "scripts", pyFile) - if not os.path.exists(pyPath): + if not Path(pyPath).exists(): pyPath = os.path.join( os.environ["GRASS_ADDON_BASE"], "scripts", pyFile ) - if not os.path.exists(pyPath): + if not Path(pyPath).exists(): GError( parent=self._guiparent, message=_("Module <%s> not found.") % command[0], diff --git a/gui/wxpython/core/globalvar.py b/gui/wxpython/core/globalvar.py index 9c4050365ac..a50950c62cd 100644 --- a/gui/wxpython/core/globalvar.py +++ b/gui/wxpython/core/globalvar.py @@ -200,7 +200,7 @@ def UpdateGRASSAddOnCommands(eList=None): nCmd = 0 pathList = os.getenv("PATH", "").split(os.pathsep) for path in addonPath.split(os.pathsep): - if not os.path.exists(path) or not os.path.isdir(path): + if not Path(path).exists() or not Path(path).is_dir(): continue # check if addon is in the path diff --git a/gui/wxpython/core/render.py b/gui/wxpython/core/render.py index d3a4522fc94..d20c051bb44 100644 --- a/gui/wxpython/core/render.py +++ b/gui/wxpython/core/render.py @@ -276,7 +276,7 @@ def IsHidden(self): def IsRendered(self) -> bool: """!Check if layer was rendered (if the image file exists)""" - return bool(os.path.exists(self.mapfile)) + return bool(Path(self.mapfile).exists()) def SetType(self, ltype): """Set layer type""" @@ -531,7 +531,7 @@ def _init(self): self.layers = [] # re-render from scratch - if os.path.exists(self.Map.mapfile): + if Path(self.Map.mapfile).exists(): os.remove(self.Map.mapfile) def _checkRenderedSizes(self, env, layers): diff --git a/gui/wxpython/core/settings.py b/gui/wxpython/core/settings.py index e0758a482d6..3e870ecdaa1 100644 --- a/gui/wxpython/core/settings.py +++ b/gui/wxpython/core/settings.py @@ -891,9 +891,9 @@ def ReadSettingsFile(self, settings=None): if settings is None: settings = self.userSettings - if os.path.exists(self.filePath): + if Path(self.filePath).exists(): self._readFile(settings) - elif os.path.exists(self.legacyFilePath): + elif Path(self.legacyFilePath).exists(): self._readLegacyFile(settings) # set environment variables @@ -982,7 +982,7 @@ def SaveToFile(self, settings=None): settings = self.userSettings dirPath = GetSettingsPath() - if not os.path.exists(dirPath): + if not Path(dirPath).exists(): try: os.mkdir(dirPath) except OSError: diff --git a/gui/wxpython/core/toolboxes.py b/gui/wxpython/core/toolboxes.py index beff6291f3e..9f05ecdac8e 100644 --- a/gui/wxpython/core/toolboxes.py +++ b/gui/wxpython/core/toolboxes.py @@ -57,14 +57,14 @@ def GetSettingsPath(): def _getUserToolboxesFile(): userToolboxesFile = os.path.join(GetSettingsPath(), "toolboxes", "toolboxes.xml") - if not os.path.exists(userToolboxesFile): + if not Path(userToolboxesFile).exists(): userToolboxesFile = None return userToolboxesFile def _getUserMainMenuFile(): userMainMenuFile = os.path.join(GetSettingsPath(), "toolboxes", "main_menu.xml") - if not os.path.exists(userMainMenuFile): + if not Path(userMainMenuFile).exists(): userMainMenuFile = None return userMainMenuFile @@ -96,7 +96,7 @@ def toolboxesOutdated(): """Removes auto-generated menudata.xml to let gui regenerate it next time it starts.""" path = os.path.join(GetSettingsPath(), "toolboxes", "menudata.xml") - if os.path.exists(path): + if Path(path).exists(): try_remove(path) @@ -118,7 +118,7 @@ def getMenudataFile(userRootFile, newFile, fallback): distributionRootFile = os.path.join(WXGUIDIR, "xml", userRootFile) userRootFile = os.path.join(GetSettingsPath(), "toolboxes", userRootFile) - if not os.path.exists(userRootFile): + if not Path(userRootFile).exists(): userRootFile = None # always create toolboxes directory if does not exist yet @@ -133,7 +133,7 @@ def getMenudataFile(userRootFile, newFile, fallback): # when any of main_menu.xml or toolboxes.xml are changed, # generate new menudata.xml - if os.path.exists(menudataFile): + if Path(menudataFile).exists(): # remove menu file when there is no main_menu and toolboxes if not _getUserToolboxesFile() and (not userRootFile): os.remove(menudataFile) @@ -217,7 +217,7 @@ def _setupToolboxes(): """Create 'toolboxes' directory if doesn't exist.""" basePath = GetSettingsPath() path = os.path.join(basePath, "toolboxes") - if not os.path.exists(basePath): + if not Path(basePath).exists(): return None if _createPath(path): @@ -227,7 +227,7 @@ def _setupToolboxes(): def _createPath(path): """Creates path (for toolboxes) if it doesn't exist'""" - if not os.path.exists(path): + if not Path(path).exists(): try: os.mkdir(path) except OSError as e: diff --git a/gui/wxpython/core/utils.py b/gui/wxpython/core/utils.py index 02f134aea79..32f40289a00 100644 --- a/gui/wxpython/core/utils.py +++ b/gui/wxpython/core/utils.py @@ -22,6 +22,7 @@ import re import inspect import operator +from pathlib import Path from string import digits from typing import TYPE_CHECKING @@ -826,7 +827,7 @@ def StoreEnvVariable(key, value=None, envFile=None): # read env file environ = {} lineSkipped = [] - if os.path.exists(envFile): + if Path(envFile).exists(): try: with open(envFile) as fd: for line in fd: diff --git a/gui/wxpython/core/watchdog.py b/gui/wxpython/core/watchdog.py index 76302aeea0a..8e316a22c05 100644 --- a/gui/wxpython/core/watchdog.py +++ b/gui/wxpython/core/watchdog.py @@ -176,12 +176,12 @@ def ScheduleWatchCurrentMapset(self): ) for element, directory in self._elements_dirs: path = os.path.join(mapset_path, directory) - if not os.path.exists(path): + if not Path(path).exists(): try: os.mkdir(path) except OSError: pass - if os.path.exists(path): + if Path(path).exists(): self._observer.schedule( MapWatch(self._patterns, element, self._evt_handler), path=path, diff --git a/gui/wxpython/gcp/manager.py b/gui/wxpython/gcp/manager.py index 4d4347d057d..e151f09e3c2 100644 --- a/gui/wxpython/gcp/manager.py +++ b/gui/wxpython/gcp/manager.py @@ -647,7 +647,7 @@ def OnVGroup(self, event): self.grassdatabase, self.xylocation, self.xymapset, "vector" ) - if os.path.exists(vector_dir): + if Path(vector_dir).exists(): dlg = VectGroup( parent=self, id=wx.ID_ANY, @@ -1104,7 +1104,7 @@ def __init__( } # make a backup of the current points file - if os.path.exists(self.file["points"]): + if Path(self.file["points"]).exists(): shutil.copy(self.file["points"], self.file["points_bak"]) # polynomial order transformation for georectification @@ -1928,10 +1928,10 @@ def OnQuit(self, event): self.SaveGCPs(None) elif ret == wx.NO: # restore POINTS file from backup - if os.path.exists(self.file["points_bak"]): + if Path(self.file["points_bak"]).exists(): shutil.copy(self.file["points_bak"], self.file["points"]) - if os.path.exists(self.file["points_bak"]): + if Path(self.file["points_bak"]).exists(): os.unlink(self.file["points_bak"]) self.SrcMap.Clean() @@ -2705,7 +2705,7 @@ def MakeVGroup(self): dirname = os.path.dirname(self.vgrpfile) - if not os.path.exists(dirname): + if not Path(dirname).exists(): os.makedirs(dirname) with open(self.vgrpfile, mode="w") as f: diff --git a/gui/wxpython/gmodeler/panels.py b/gui/wxpython/gmodeler/panels.py index dcfae3d3ed5..506f6169305 100644 --- a/gui/wxpython/gmodeler/panels.py +++ b/gui/wxpython/gmodeler/panels.py @@ -901,7 +901,7 @@ def OnModelSaveAs(self, event=None): if filename[-4:] != ".gxm": filename += ".gxm" - if os.path.exists(filename): + if Path(filename).exists(): dlg = wx.MessageDialog( parent=self, message=_( @@ -1742,7 +1742,7 @@ def SaveAs(self, force=False): if filename[-len(file_ext) - 1 :] != f".{file_ext}": filename += f".{file_ext}" - if os.path.exists(filename): + if Path(filename).exists(): dlg = wx.MessageDialog( self, message=_( diff --git a/gui/wxpython/gui_core/ghelp.py b/gui/wxpython/gui_core/ghelp.py index ef187edab13..dea3a156e2a 100644 --- a/gui/wxpython/gui_core/ghelp.py +++ b/gui/wxpython/gui_core/ghelp.py @@ -277,7 +277,7 @@ def _pageInfo(self): def _pageCopyright(self): """Copyright information""" copyfile = os.path.join(os.getenv("GISBASE"), "COPYING") - if os.path.exists(copyfile): + if Path(copyfile).exists(): copytext = Path(copyfile).read_text() else: copytext = _("%s file missing") % "COPYING" @@ -304,7 +304,7 @@ def _pageCopyright(self): def _pageLicense(self): """Licence about""" licfile = os.path.join(os.getenv("GISBASE"), "GPL.TXT") - if os.path.exists(licfile): + if Path(licfile).exists(): with open(licfile) as licenceFile: license = "".join(licenceFile.readlines()) else: @@ -357,7 +357,7 @@ def _pageCredit(self): """Credit about""" # credits authfile = os.path.join(os.getenv("GISBASE"), "AUTHORS") - if os.path.exists(authfile): + if Path(authfile).exists(): with codecs.open(authfile, encoding="utf-8", mode="r") as authorsFile: authors = "".join(authorsFile.readlines()) else: @@ -384,7 +384,7 @@ def _pageContributors(self, extra=False): contribfile = os.path.join(os.getenv("GISBASE"), "contributors_extra.csv") else: contribfile = os.path.join(os.getenv("GISBASE"), "contributors.csv") - if os.path.exists(contribfile): + if Path(contribfile).exists(): contribs = [] errLines = [] with codecs.open(contribfile, encoding="utf-8", mode="r") as contribFile: @@ -467,7 +467,7 @@ def _pageContributors(self, extra=False): def _pageTranslators(self): """Translators info""" translatorsfile = os.path.join(os.getenv("GISBASE"), "translators.csv") - if os.path.exists(translatorsfile): + if Path(translatorsfile).exists(): translators = {} errLines = [] with codecs.open(translatorsfile, encoding="utf-8", mode="r") as fd: @@ -538,7 +538,7 @@ def _pageTranslators(self): flag = os.path.join( globalvar.ICONDIR, "flags", "%s.png" % lang.lower() ) - if os.path.exists(flag): + if Path(flag).exists(): flagBitmap = wx.StaticBitmap( translatorswin, wx.ID_ANY, @@ -647,7 +647,7 @@ def _pageStats(self): """Translation statistics info""" fname = "translation_status.json" statsfile = os.path.join(os.getenv("GISBASE"), fname) - if os.path.exists(statsfile): + if Path(statsfile).exists(): import json with open(statsfile) as statsFile: @@ -763,7 +763,7 @@ def __init__(self, parent, command, text, **kwargs): self.markdown = True # check if mkdocs is used (add slash at the end) self.fspath = os.path.join(os.getenv("GISBASE"), "docs", "mkdocs", "site", "") - if not os.path.exists(self.fspath): + if not Path(self.fspath).exists(): self.markdown = False self.fspath = os.path.join(os.getenv("GISBASE"), "docs", "html", "") diff --git a/gui/wxpython/gui_core/menu.py b/gui/wxpython/gui_core/menu.py index cef3ae8f853..876b56a4ec8 100644 --- a/gui/wxpython/gui_core/menu.py +++ b/gui/wxpython/gui_core/menu.py @@ -25,6 +25,7 @@ import re import os +from pathlib import Path import wx from core import globalvar @@ -402,7 +403,7 @@ def _onFileHistory(self, event): file_index = event.GetId() - wx.ID_FILE1 path = self._filehistory.GetHistoryFile(file_index) - if not os.path.exists(path): + if not Path(path).exists(): self.RemoveFileFromHistory(file_index) file_exists = False self.file_requested.emit( @@ -442,7 +443,7 @@ def RemoveNonExistentFiles(self): """Remove non existent files from the history""" for i in reversed(range(self._filehistory.GetCount())): file = self._filehistory.GetHistoryFile(index=i) - if not os.path.exists(file): + if not Path(file).exists(): self._filehistory.RemoveFileFromHistory(i=i) self._filehistory.Save(self._config) diff --git a/gui/wxpython/gui_core/pyedit.py b/gui/wxpython/gui_core/pyedit.py index e5efb4b0830..37c32f0a254 100644 --- a/gui/wxpython/gui_core/pyedit.py +++ b/gui/wxpython/gui_core/pyedit.py @@ -411,7 +411,7 @@ def SaveAs(self): if filename[-3:] != ".py": filename += ".py" - if os.path.exists(filename): + if Path(filename).exists(): dlg = wx.MessageDialog( parent=self.guiparent, message=_( diff --git a/gui/wxpython/gui_core/widgets.py b/gui/wxpython/gui_core/widgets.py index 13f3d6f5846..62a9b96eb08 100644 --- a/gui/wxpython/gui_core/widgets.py +++ b/gui/wxpython/gui_core/widgets.py @@ -56,6 +56,7 @@ import re from bisect import bisect from datetime import datetime +from pathlib import Path from core.globalvar import wxPythonPhoenix import wx @@ -1554,7 +1555,7 @@ def _loadSettings(self): """ data = {} - if not os.path.exists(self.settingsFile): + if not Path(self.settingsFile).exists(): return data try: @@ -1711,7 +1712,7 @@ def GetPictureBitmap(self, name): return self.bitmaps[name] path = self._getPath(name) - if os.path.exists(path): + if Path(path).exists(): bitmap = wx.Bitmap(path) self.bitmaps[name] = bitmap return bitmap diff --git a/gui/wxpython/iclass/frame.py b/gui/wxpython/iclass/frame.py index c70ca9f6e4d..9da3e40c11d 100644 --- a/gui/wxpython/iclass/frame.py +++ b/gui/wxpython/iclass/frame.py @@ -22,6 +22,7 @@ import os import tempfile from ctypes import byref, pointer +from pathlib import Path import wx @@ -1252,7 +1253,7 @@ def OnSaveSigFile(self, event): dlg = IClassSignatureFileDialog(self, file=self.sigFile) if dlg.ShowModal() == wx.ID_OK: - if os.path.exists(dlg.GetFileName(fullPath=True)): + if Path(dlg.GetFileName(fullPath=True)).exists(): qdlg = wx.MessageDialog( parent=self, message=_( diff --git a/gui/wxpython/icons/icon.py b/gui/wxpython/icons/icon.py index 77ef956278b..9f8ed03cc48 100644 --- a/gui/wxpython/icons/icon.py +++ b/gui/wxpython/icons/icon.py @@ -18,6 +18,7 @@ import os import sys import copy +from pathlib import Path import wx @@ -41,7 +42,7 @@ # join paths try: - if iconPath and not os.path.exists(iconPath): + if iconPath and not Path(iconPath).exists(): raise OSError for key, img in iconSet.items(): diff --git a/gui/wxpython/image2target/ii2t_gis_set.py b/gui/wxpython/image2target/ii2t_gis_set.py index a4d406e4599..37248e06141 100644 --- a/gui/wxpython/image2target/ii2t_gis_set.py +++ b/gui/wxpython/image2target/ii2t_gis_set.py @@ -997,7 +997,7 @@ def OnSetDatabase(self, event): """Database set""" gisdbase = self.tgisdbase.GetValue() self._hideMessage() - if not os.path.exists(gisdbase): + if not Path(gisdbase).exists(): self._showError(_("Path '%s' doesn't exist.") % gisdbase) return diff --git a/gui/wxpython/image2target/ii2t_manager.py b/gui/wxpython/image2target/ii2t_manager.py index c8c5aeaddc3..1c86785323e 100644 --- a/gui/wxpython/image2target/ii2t_manager.py +++ b/gui/wxpython/image2target/ii2t_manager.py @@ -488,10 +488,9 @@ def OnLocation(self, event): tmplist = [p.name for p in Path(self.grassdatabase, self.xylocation).iterdir()] self.mapsetList = [] for item in tmplist: - if os.path.isdir( - os.path.join(self.grassdatabase, self.xylocation, item) - ) and os.path.exists( - os.path.join(self.grassdatabase, self.xylocation, item, "WIND") + if ( + os.path.isdir(os.path.join(self.grassdatabase, self.xylocation, item)) + and Path(self.grassdatabase, self.xylocation, item, "WIND").exists() ): if item != "PERMANENT": self.mapsetList.append(item) @@ -1088,7 +1087,7 @@ def __init__( } # make a backup of the current points file - if os.path.exists(self.file["control_points"]): + if Path(self.file["control_points"]).exists(): shutil.copy(self.file["control_points"], self.file["control_points_bak"]) # polynomial order transformation for georectification @@ -1449,7 +1448,7 @@ def SetGCPData(self, coordtype, coord, mapdisp=None, confirm=False): self.mapcoordlist[key][4] = coord[0] self.mapcoordlist[key][5] = coord[1] # ADD ELEVATION FROM MAP AS HEIGHT PARAMETER - if os.path.exists(self.file["elevation"]): + if Path(self.file["elevation"]).exists(): # Parse the i.ortho.elev generated file # Get all lines from file lines = Path(self.file["elevation"]).read_text().splitlines() @@ -1870,12 +1869,12 @@ def OnQuit(self, event): self.SaveGCPs(None) elif ret == wx.NO: # restore POINTS file from backup - if os.path.exists(self.file["control_points_bak"]): + if Path(self.file["control_points_bak"]).exists(): shutil.copy( self.file["control_points_bak"], self.file["control_points"] ) - if os.path.exists(self.file["control_points_bak"]): + if Path(self.file["control_points_bak"]).exists(): os.unlink(self.file["control_points_bak"]) self.SrcMap.Clean() diff --git a/gui/wxpython/lmgr/frame.py b/gui/wxpython/lmgr/frame.py index 22714ee01fe..1ab5692d980 100644 --- a/gui/wxpython/lmgr/frame.py +++ b/gui/wxpython/lmgr/frame.py @@ -1223,7 +1223,7 @@ def OnRunScript(self, event): if not filename: return False - if not os.path.exists(filename): + if not Path(filename).exists(): GError( parent=self, message=_("Script file '%s' doesn't exist. Operation canceled.") @@ -1462,8 +1462,9 @@ def OnSystemInfo(self, event): sys.stderr.write(_("Unable to get GRASS version\n")) # check also OSGeo4W on MS Windows - if sys.platform == "win32" and not os.path.exists( - os.path.join(os.getenv("GISBASE"), "WinGRASS-README.url") + if ( + sys.platform == "win32" + and not Path(os.getenv("GISBASE"), "WinGRASS-README.url").exists() ): osgeo4w = " (OSGeo4W)" else: diff --git a/gui/wxpython/lmgr/workspace.py b/gui/wxpython/lmgr/workspace.py index 41eea57657b..7f4d2bcc7c4 100644 --- a/gui/wxpython/lmgr/workspace.py +++ b/gui/wxpython/lmgr/workspace.py @@ -382,7 +382,7 @@ def SaveAs(self): if filename[-4:] != ".gxw": filename += ".gxw" - if os.path.exists(filename): + if Path(filename).exists(): dlg = wx.MessageDialog( self.lmgr, message=_( diff --git a/gui/wxpython/main_window/frame.py b/gui/wxpython/main_window/frame.py index 84ad713ffa5..ebcb420dbd5 100644 --- a/gui/wxpython/main_window/frame.py +++ b/gui/wxpython/main_window/frame.py @@ -1379,7 +1379,7 @@ def OnRunScript(self, event): if not filename: return False - if not os.path.exists(filename): + if not Path(filename).exists(): GError( parent=self, message=_("Script file '%s' doesn't exist. Operation canceled.") @@ -1618,8 +1618,9 @@ def OnSystemInfo(self, event): sys.stderr.write(_("Unable to get GRASS version\n")) # check also OSGeo4W on MS Windows - if sys.platform == "win32" and not os.path.exists( - os.path.join(os.getenv("GISBASE"), "WinGRASS-README.url") + if ( + sys.platform == "win32" + and not Path(os.getenv("GISBASE"), "WinGRASS-README.url").exists() ): osgeo4w = " (OSGeo4W)" else: diff --git a/gui/wxpython/modules/colorrules.py b/gui/wxpython/modules/colorrules.py index c321699e816..809307c7eca 100644 --- a/gui/wxpython/modules/colorrules.py +++ b/gui/wxpython/modules/colorrules.py @@ -665,7 +665,7 @@ def OnSaveRulesFile(self, event): if not path: return - if os.path.exists(path): + if Path(path).exists(): dlgOw = wx.MessageDialog( self, message=_( @@ -692,7 +692,7 @@ def OnSaveRulesFile(self, event): def OnLoadRulesFile(self, event): """Load color table from file""" path = event.GetString() - if not os.path.exists(path): + if not Path(path).exists(): return self.rulesPanel.Clear() diff --git a/gui/wxpython/modules/import_export.py b/gui/wxpython/modules/import_export.py index 8bd533c0e1d..0ba706191b6 100644 --- a/gui/wxpython/modules/import_export.py +++ b/gui/wxpython/modules/import_export.py @@ -494,7 +494,7 @@ def OnRun(self, event): idsn = dsn if "PG:" in dsn: idsn = f"{dsn} table={layer}" - elif os.path.exists(idsn): + elif Path(idsn).exists(): try: from osgeo import gdal diff --git a/gui/wxpython/nviz/tools.py b/gui/wxpython/nviz/tools.py index 43249e416c6..c0e10b6e197 100644 --- a/gui/wxpython/nviz/tools.py +++ b/gui/wxpython/nviz/tools.py @@ -19,7 +19,6 @@ @author Anna Kratochvilova (Google SoC 2011) """ -import os import sys import copy @@ -2783,7 +2782,7 @@ def OnSaveAnimation(self, event): if not prefix: GMessage(parent=self, message=_("No file prefix given.")) return - if not os.path.exists(dir): + if not Path(dir).exists(): GMessage(parent=self, message=_("Directory %s does not exist.") % dir) return diff --git a/gui/wxpython/photo2image/ip2i_manager.py b/gui/wxpython/photo2image/ip2i_manager.py index 9b8aa7d71d5..11aeaad9613 100644 --- a/gui/wxpython/photo2image/ip2i_manager.py +++ b/gui/wxpython/photo2image/ip2i_manager.py @@ -30,6 +30,7 @@ import sys import shutil from copy import copy +from pathlib import Path import wx from wx.lib.mixins.listctrl import ColumnSorterMixin, ListCtrlAutoWidthMixin @@ -407,7 +408,7 @@ def __init__( } # make a backup of the current points file if exists - if os.path.exists(self.file["points"]): + if Path(self.file["points"]).exists(): shutil.copy(self.file["points"], self.file["points_bak"]) shutil.copy(self.file["points"], self.file["ref_points"]) GMessage(_("A POINTS file exists, renaming it to POINTS_BAK")) @@ -1187,11 +1188,11 @@ def OnQuit(self, event): self.SaveGCPs(None) elif ret == wx.NO: # restore POINTS file from backup - if os.path.exists(self.file["points_bak"]): + if Path(self.file["points_bak"]).exists(): shutil.copy(self.file["points_bak"], self.file["points"]) shutil.copy(self.file["points_bak"], self.file["ref_points"]) - if os.path.exists(self.file["points_bak"]): + if Path(self.file["points_bak"]).exists(): os.unlink(self.file["points_bak"]) self.SrcMap.Clean() diff --git a/gui/wxpython/psmap/dialogs.py b/gui/wxpython/psmap/dialogs.py index 5b31cf596e2..3245d9bc107 100644 --- a/gui/wxpython/psmap/dialogs.py +++ b/gui/wxpython/psmap/dialogs.py @@ -4972,7 +4972,7 @@ def _scalebarPanel(self): os.path.join(globalvar.IMGDIR, "scalebar-simple.png"), ) for item, path in zip(["fancy", "simple"], imagePath, strict=True): - bitmap = EmptyBitmap(0, 0) if not os.path.exists(path) else wx.Bitmap(path) + bitmap = EmptyBitmap(0, 0) if not Path(path).exists() else wx.Bitmap(path) self.sbCombo.Append(item="", bitmap=bitmap, clientData=item[0]) # self.sbCombo.Append( # item="simple", @@ -5988,7 +5988,7 @@ def OnImageSelectionChanged(self, event): return basePath = self.imagePanel.image["dir"].GetValue() file = os.path.join(basePath, imageName) - if not os.path.exists(file): + if not Path(file).exists(): return if os.path.splitext(file)[1].lower() == ".eps": diff --git a/gui/wxpython/psmap/instructions.py b/gui/wxpython/psmap/instructions.py index cd873a5cf06..635a2d96f53 100644 --- a/gui/wxpython/psmap/instructions.py +++ b/gui/wxpython/psmap/instructions.py @@ -1135,7 +1135,7 @@ def Read(self, instruction, text, **kwargs): except (IndexError, ValueError): GError(_("Failed to read instruction %s") % instruction) return False - if not os.path.exists(instr["epsfile"]): + if not Path(instr["epsfile"]).exists(): GError( _("Failed to read instruction %(inst)s: file %(file)s not found.") % {"inst": instruction, "file": instr["epsfile"]} diff --git a/gui/wxpython/rlisetup/functions.py b/gui/wxpython/rlisetup/functions.py index 6a6eec30515..4c681af9cf2 100644 --- a/gui/wxpython/rlisetup/functions.py +++ b/gui/wxpython/rlisetup/functions.py @@ -7,6 +7,7 @@ import wx import os import sys +from pathlib import Path from grass.script import core as grass from core.gcmd import GError @@ -58,7 +59,7 @@ def retRLiPath(): grass_config_dir = os.path.join(os.getenv("HOME"), grass_config_dirname) rlipath = os.path.join(grass_config_dir, "r.li") - if os.path.exists(rlipath): + if Path(rlipath).exists(): return rlipath os.mkdir(rlipath) return rlipath diff --git a/gui/wxpython/startup/locdownload.py b/gui/wxpython/startup/locdownload.py index 3fb45c05ab9..a9383f53dc8 100644 --- a/gui/wxpython/startup/locdownload.py +++ b/gui/wxpython/startup/locdownload.py @@ -22,6 +22,8 @@ import textwrap import time +from pathlib import Path + import wx from wx.lib.newevent import NewEvent @@ -322,7 +324,7 @@ def DownloadItem(self, item): url = item["url"] dirname = location_name_from_url(url) destination = os.path.join(self.database, dirname) - if os.path.exists(destination): + if Path(destination).exists(): self._error( _( "Project name {name} already exists in {path}, download canceled" @@ -379,7 +381,7 @@ def CheckItem(self, item): url = item["url"] dirname = location_name_from_url(url) destination = os.path.join(self.database, dirname) - if os.path.exists(destination): + if Path(destination).exists(): self._warning( _("Project named {name} already exists, rename it first").format( name=dirname diff --git a/gui/wxpython/tplot/frame.py b/gui/wxpython/tplot/frame.py index abe3f62b938..506e1b50db6 100755 --- a/gui/wxpython/tplot/frame.py +++ b/gui/wxpython/tplot/frame.py @@ -19,7 +19,6 @@ @author start stvds support Matej Krejci """ -import os from itertools import cycle from pathlib import Path import numpy as np @@ -1001,7 +1000,7 @@ def OnRedraw(self, event=None): self.init() self.csvpath = self.csvButton.GetValue() self.header = self.headerCheck.IsChecked() - if os.path.exists(self.csvpath) and not self.overwrite: + if Path(self.csvpath).exists() and not self.overwrite: dlg = wx.MessageDialog( self, _("{pa} already exists, do you want to overwrite?").format( diff --git a/gui/wxpython/wxplot/profile.py b/gui/wxpython/wxplot/profile.py index ddd6fe6b1cd..537e59ff101 100644 --- a/gui/wxpython/wxplot/profile.py +++ b/gui/wxpython/wxplot/profile.py @@ -15,7 +15,6 @@ @author Michael Barton, Arizona State University """ -import os import sys import math import numpy as np @@ -421,7 +420,7 @@ def SaveProfileToFile(self, event): path = dlg.GetPath() for r in self.rasterList: pfile.append(path + "_" + str(r.replace("@", "_")) + ".csv") - if os.path.exists(pfile[-1]): + if Path(pfile[-1]).exists(): dlgOv = wx.MessageDialog( self, message=_( diff --git a/imagery/i.cluster/testsuite/test_i_cluster.py b/imagery/i.cluster/testsuite/test_i_cluster.py index a65170ca4ce..779286160f6 100644 --- a/imagery/i.cluster/testsuite/test_i_cluster.py +++ b/imagery/i.cluster/testsuite/test_i_cluster.py @@ -97,7 +97,7 @@ def test_sample_interval(self): """Test that sample interval affects the number of cells sampled""" sample_interval = (2, 2) report_file = "sample_report.txt" - self.addCleanup(os.remove, report_file) if os.path.exists(report_file) else None + self.addCleanup(os.remove, report_file) if Path(report_file).exists() else None self.assertModule( "i.cluster", @@ -123,8 +123,8 @@ def test_convergence_parameters(self): high_percent = 99.5 low_report = "low_percent_report.txt" high_report = "high_percent_report.txt" - self.addCleanup(os.remove, low_report) if os.path.exists(low_report) else None - self.addCleanup(os.remove, high_report) if os.path.exists(high_report) else None + self.addCleanup(os.remove, low_report) if Path(low_report).exists() else None + self.addCleanup(os.remove, high_report) if Path(high_report).exists() else None self.assertModule( "i.cluster", group=self.group_name, @@ -205,7 +205,7 @@ def minimum_pairwise_distance(self, means): def test_separation_parameter1(self): """Test the effect of the separation parameter on cluster separation quality.""" report_file = "separation_report.txt" - self.addCleanup(os.remove, report_file) if os.path.exists(report_file) else None + self.addCleanup(os.remove, report_file) if Path(report_file).exists() else None sig_file_default = self.signature_file + "_sep0" self.assertModule( "i.cluster", diff --git a/imagery/i.landsat.toar/testsuite/test_i_landsat_toar.py b/imagery/i.landsat.toar/testsuite/test_i_landsat_toar.py index cffa36709be..2786feed1af 100644 --- a/imagery/i.landsat.toar/testsuite/test_i_landsat_toar.py +++ b/imagery/i.landsat.toar/testsuite/test_i_landsat_toar.py @@ -84,7 +84,7 @@ def tearDownClass(cls): test_rasters += [f"{cls.output_prefix}{suffix}{b}" for b in bands] all_rasters = input_rasters + output_rasters + test_rasters cls.runModule("g.remove", flags="f", type="raster", name=all_rasters) - if os.path.exists(cls.metfile): + if Path(cls.metfile).exists(): os.remove(cls.metfile) def test_reflectance_and_temperature_conversion_with_scale(self): diff --git a/imagery/i.rectify/testsuite/test_i_rectify.py b/imagery/i.rectify/testsuite/test_i_rectify.py index 4de3283a4b7..e7d269c805a 100644 --- a/imagery/i.rectify/testsuite/test_i_rectify.py +++ b/imagery/i.rectify/testsuite/test_i_rectify.py @@ -90,10 +90,10 @@ def tearDownClass(cls): """Remove input rasters, group, and temporary files.""" cls.runModule("g.remove", type="raster", name=cls.tmp_rasters, flags="f") cls.runModule("g.remove", type="group", name=cls.group, flags="f") - if os.path.exists(cls.points_path): + if Path(cls.points_path).exists(): os.remove(cls.points_path) for f in cls.tmp_files: - if os.path.exists(f): + if Path(f).exists(): os.remove(f) def _run_and_check( diff --git a/imagery/i.target/testsuite/test_i_target.py b/imagery/i.target/testsuite/test_i_target.py index d2c03b218be..17916e129f0 100644 --- a/imagery/i.target/testsuite/test_i_target.py +++ b/imagery/i.target/testsuite/test_i_target.py @@ -1,4 +1,5 @@ import os +from pathlib import Path import grass.script as gs from grass.gunittest.case import TestCase from grass.gunittest.main import test @@ -45,11 +46,11 @@ def test_current_location_flag(self): group = self.groups[0] target_file = self._target_path(group) - if os.path.exists(target_file): + if Path(target_file).exists(): os.remove(target_file) self.assertModule("i.target", flags="c", group=group) - self.assertTrue(os.path.exists(target_file)) + self.assertTrue(Path(target_file).exists()) current_env = gs.gisenv() loc, mset = self._get_target_values(group) diff --git a/lib/gis/testsuite/test_gis_lib_getl.py b/lib/gis/testsuite/test_gis_lib_getl.py index 34f037e79cb..1a32eb6a2a6 100644 --- a/lib/gis/testsuite/test_gis_lib_getl.py +++ b/lib/gis/testsuite/test_gis_lib_getl.py @@ -5,8 +5,8 @@ import os import ctypes -import pathlib import unittest +from pathlib import Path import grass.lib.gis as libgis from grass.gunittest.case import TestCase @@ -24,7 +24,7 @@ def setUpClass(cls): cls.libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) cls.libc.fopen.restype = ctypes.POINTER(libgis.FILE) cls.libc.fopen.argtypes = [ctypes.c_char_p, ctypes.c_char_p] - cls.file_path = pathlib.Path("test.txt") + cls.file_path = Path("test.txt") def tearDown(self): self.file_path.unlink() diff --git a/lib/init/grass.py b/lib/init/grass.py index fe9863ff525..270803ddc81 100755 --- a/lib/init/grass.py +++ b/lib/init/grass.py @@ -623,7 +623,7 @@ def check_gui(expected_gui): "Please check your installation or set the GRASS_PYTHON" " environment variable." ) - if not os.path.exists(wxpath("wxgui.py")): + if not Path(wxpath("wxgui.py")).exists(): msg = _("GRASS GUI not found. Please check your installation.") if msg: warning(_("{}\nSwitching to text based interface mode.").format(msg)) @@ -675,7 +675,7 @@ def create_location(gisdbase, location, geostring) -> None: def can_create_location(gisdbase: StrPath, location) -> bool: """Checks if location can be created""" path = os.path.join(gisdbase, location) - return not os.path.exists(path) + return not Path(path).exists() def cannot_create_location_reason(gisdbase: StrPath, location: str) -> str: @@ -1363,10 +1363,10 @@ def script_path(batch_job): script_in_addon_path = os.path.join( os.environ["GRASS_ADDON_BASE"], "scripts", batch_job[0] ) - if script_in_addon_path and os.path.exists(script_in_addon_path): + if script_in_addon_path and Path(script_in_addon_path).exists(): batch_job[0] = script_in_addon_path return script_in_addon_path - if os.path.exists(batch_job[0]): + if Path(batch_job[0]).exists(): return batch_job[0] try: @@ -1647,7 +1647,7 @@ def sh_like_startup(location, location_name, grass_env_file, sh): # Here we create the file in the Mapset directory if it exists in the # user's home directory. sudo_success_file = ".sudo_as_admin_successful" - if os.path.exists(os.path.join(userhome, sudo_success_file)): + if Path(userhome, sudo_success_file).exists(): try: # Open with append so that if the file already exists there # isn't any error. @@ -1780,7 +1780,7 @@ def print_params(params) -> None: dev_params = ["arch", "compiler", "build", "date"] if any(param in dev_params for param in params): plat = gpath("include", "Make", "Platform.make") - if not os.path.exists(plat): + if not Path(plat).exists(): fatal(_("Please install the GRASS development package")) with open(plat) as fileplat: # this is in fact require only for some, but prepare it anyway @@ -2132,23 +2132,23 @@ def find_path_to_grass_python_package() -> tuple[str, bool]: else: # The "@...@" variables are being substituted during build process path_from_variable = os.path.normpath(r"@GRASS_PYDIR@") - if os.path.exists(path_from_variable): + if Path(path_from_variable).exists(): return path_from_variable, True base = Path(__file__).parent.parent / "lib" path_from_context = base / "grass" / "etc" / "python" - if os.path.exists(path_from_context): + if path_from_context.exists(): return str(path_from_context), True major = "@GRASS_VERSION_MAJOR@" minor = "@GRASS_VERSION_MINOR@" # Try a run-together version number for the directory (long-used standard). path_from_context = base / f"grass{major}{minor}" / "etc" / "python" - if os.path.exists(path_from_context): + if path_from_context.exists(): return str(path_from_context), True # Try a dotted version number (more common standard). path_from_context = base / f"grass{major}.{minor}" / "etc" / "python" - if os.path.exists(path_from_context): + if path_from_context.exists(): return str(path_from_context), True return path_from_variable, False diff --git a/locale/grass_po_stats.py b/locale/grass_po_stats.py index b12ea6464f7..db8106d51f5 100644 --- a/locale/grass_po_stats.py +++ b/locale/grass_po_stats.py @@ -155,7 +155,7 @@ def main(in_dirpath, out_josonpath): languages = read_po_files(in_dirpath) stats = get_stats(languages, in_dirpath) - if os.path.exists(out_josonpath): + if Path(out_josonpath).exists(): os.remove(out_josonpath) writejson(stats, out_josonpath) diff --git a/man/build.py b/man/build.py index 1de2de518d2..a7e9f5817c9 100644 --- a/man/build.py +++ b/man/build.py @@ -71,8 +71,8 @@ def try_mkdir(path): def replace_file(name): temp = name + ".tmp" if ( - os.path.exists(name) - and os.path.exists(temp) + Path(name).exists() + and Path(temp).exists() and read_file(name) == read_file(temp) ): os.remove(temp) diff --git a/man/build_rest.py b/man/build_rest.py index 7eba6d7fc16..8bb048f1de0 100644 --- a/man/build_rest.py +++ b/man/build_rest.py @@ -289,8 +289,8 @@ def try_mkdir(path): def replace_file(name): temp = name + ".tmp" if ( - os.path.exists(name) - and os.path.exists(temp) + Path(name).exists() + and Path(temp).exists() and read_file(name) == read_file(temp) ): os.remove(temp) diff --git a/pyproject.toml b/pyproject.toml index 18cac348ee7..c39912b8fae 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -217,7 +217,6 @@ ignore = [ "PTH106", # os-rmdir "PTH107", # os-remove "PTH108", # os-unlink - "PTH110", # os-path-exists "PTH111", # os-path-expanduser "PTH112", # os-path-isdir "PTH113", # os-path-isfile @@ -353,7 +352,7 @@ ignore = [ "man/build_rest.py" = ["PLW1514", "PTH208"] "man/build_topics.py" = ["PLW1514"] "man/parser_standard_options.py" = ["PLW1514"] -"python/grass/__init__.py" = ["PYI056"] +"python/grass/__init__.py" = ["PTH110", "PYI056"] "python/grass/exp*/tests/grass_script_mapset_session_test.py" = ["SIM117"] "python/grass/exp*/tests/grass_script_tmp_mapset_session_test.py" = ["SIM117"] "python/grass/gunittest/case.py" = ["PLW1514", "PT009"] diff --git a/python/grass/app/data.py b/python/grass/app/data.py index 5f7cec287dc..e4936bcb4f2 100644 --- a/python/grass/app/data.py +++ b/python/grass/app/data.py @@ -43,7 +43,7 @@ def get_possible_database_path(): # find possible database path for candidate in candidates: - if os.path.exists(candidate): + if Path(candidate).exists(): for subdir in next(os.walk(candidate))[1]: if "grassdata" in subdir.lower(): return os.path.join(candidate, subdir) @@ -83,7 +83,7 @@ def create_database_directory(): # another GRASS instance will find the data created by the first # one which is desired in the "try out GRASS" use case we are # aiming towards." - if os.path.exists(path): + if Path(path).exists(): return path try: os.mkdir(path) @@ -103,7 +103,7 @@ def _get_startup_location_in_distribution(): startup_location = os.path.join(gisbase, "demolocation") # Find out if startup location exists - if os.path.exists(startup_location): + if Path(startup_location).exists(): return startup_location return None @@ -292,7 +292,7 @@ def lock_mapset( process_id = os.getpid() if not env: env = os.environ - if not os.path.exists(mapset_path): + if not Path(mapset_path).exists(): raise MapsetLockingException(_("Path '{}' doesn't exist").format(mapset_path)) if not os.access(mapset_path, os.W_OK): error = _("Path '{}' not accessible.").format(mapset_path) diff --git a/python/grass/app/runtime.py b/python/grass/app/runtime.py index 407802c7a73..2f72088a1e9 100644 --- a/python/grass/app/runtime.py +++ b/python/grass/app/runtime.py @@ -16,6 +16,7 @@ import shutil import subprocess import sys +from pathlib import Path from . import resource_paths @@ -181,12 +182,12 @@ def append_left_main_executable_paths(paths, install_path): if WINDOWS: # Standalone installer has dependencies which are on path in other cases. path = os.path.join(install_path, "extrabin") - if os.path.exists(path): + if Path(path).exists(): paths.appendleft(path) else: # Without FHS, scripts are separated like in the source code. path = os.path.join(install_path, "scripts") - if os.path.exists(path): + if Path(path).exists(): paths.appendleft(path) @@ -201,7 +202,7 @@ def append_left_addon_paths(paths, config_dir, env): if not WINDOWS: script_path = os.path.join(addon_base, "scripts") - if os.path.exists(script_path): + if Path(script_path).exists(): paths.appendleft(script_path) paths.appendleft(os.path.join(addon_base, "bin")) diff --git a/python/grass/app/tests/grass_app_resource_paths_test.py b/python/grass/app/tests/grass_app_resource_paths_test.py index 87918c90b6c..6cd5dde7c73 100644 --- a/python/grass/app/tests/grass_app_resource_paths_test.py +++ b/python/grass/app/tests/grass_app_resource_paths_test.py @@ -1,4 +1,5 @@ import os +from pathlib import Path import pytest @@ -37,5 +38,5 @@ def test_value_not_empty(name): @pytest.mark.parametrize("name", ["GRASS_PREFIX"]) def test_value_is_directory(name): value = getattr(resource_paths, name) - assert os.path.exists(value) + assert Path(value).exists() assert os.path.isdir(value) diff --git a/python/grass/experimental/create.py b/python/grass/experimental/create.py index acd1ec6f66a..dfb1ef20a6a 100644 --- a/python/grass/experimental/create.py +++ b/python/grass/experimental/create.py @@ -1,7 +1,7 @@ """Likely going into grass.grassdb.create""" -import pathlib import tempfile +from pathlib import Path from grass.grassdb.checks import ( mapset_exists, @@ -65,7 +65,7 @@ def create_temporary_mapset(path, location=None) -> MapsetPath: The user of this function is responsible for deleting the contents of the temporary directory and the directory itself when done with it. """ - path = pathlib.Path(path) + path = Path(path) if location: path /= location tmp_dir = tempfile.mkdtemp(dir=path) diff --git a/python/grass/experimental/tests/grass_script_mapset_session_test.py b/python/grass/experimental/tests/grass_script_mapset_session_test.py index 828bdc90342..6e87b0efc2a 100644 --- a/python/grass/experimental/tests/grass_script_mapset_session_test.py +++ b/python/grass/experimental/tests/grass_script_mapset_session_test.py @@ -1,6 +1,6 @@ """Test MapsetSession""" -import os +from pathlib import Path import pytest @@ -25,9 +25,9 @@ def test_simple_create(xy_session): other_session_file = session.env["GISRC"] assert session_file != other_session_file - assert os.path.exists(other_session_file) - assert not os.path.exists(other_session_file) - assert os.path.exists(session_file) + assert Path(other_session_file).exists() + assert not Path(other_session_file).exists() + assert Path(session_file).exists() assert xy_session.env["GISRC"] @@ -48,10 +48,10 @@ def test_without_context_manager(xy_session): other_session_file = session.env["GISRC"] assert session_file != other_session_file - assert os.path.exists(other_session_file) + assert Path(other_session_file).exists() session.finish() - assert not os.path.exists(other_session_file) - assert os.path.exists(session_file) + assert not Path(other_session_file).exists() + assert Path(session_file).exists() assert xy_session.env["GISRC"] @@ -89,7 +89,7 @@ def test_create_overwrite(xy_session): ) assert len(rasters) == 1 assert rasters[0] == "a" - assert os.path.exists(session_file) + assert Path(session_file).exists() def test_ensure(xy_session): @@ -124,7 +124,7 @@ def test_ensure(xy_session): .split() ) assert sorted(rasters) == ["a", "b"] - assert os.path.exists(session_file) + assert Path(session_file).exists() def get_mapset_names(env): @@ -179,7 +179,7 @@ def test_nested_top_env(xy_session): "g.mapset", flags="p", env=session.env ).strip() assert name == session_mapset - assert os.path.exists(xy_session.env["GISRC"]) + assert Path(xy_session.env["GISRC"]).exists() def test_nested_inherited_env(xy_session): @@ -201,7 +201,7 @@ def test_nested_inherited_env(xy_session): "g.mapset", flags="p", env=session.env ).strip() assert name == session_mapset - assert os.path.exists(xy_session.env["GISRC"]) + assert Path(xy_session.env["GISRC"]).exists() @pytest.mark.parametrize("number", [1, 2, 3.1]) diff --git a/python/grass/experimental/tests/grass_script_tmp_mapset_session_test.py b/python/grass/experimental/tests/grass_script_tmp_mapset_session_test.py index f7098004527..181f1288818 100644 --- a/python/grass/experimental/tests/grass_script_tmp_mapset_session_test.py +++ b/python/grass/experimental/tests/grass_script_tmp_mapset_session_test.py @@ -1,6 +1,6 @@ """Tests of TemporaryMapsetSession""" -import os +from pathlib import Path import grass.script as gs from grass import experimental @@ -29,17 +29,17 @@ def test_with_context_manager(xy_session): other_session_file = session.env["GISRC"] assert session_file != other_session_file - assert os.path.exists(other_session_file) + assert Path(other_session_file).exists() mapset_path = session.mapset_path - assert os.path.exists(session.mapset_path) + assert Path(session.mapset_path).exists() assert not session.active - assert not os.path.exists(mapset_path) - assert not os.path.exists(other_session_file) + assert not Path(mapset_path).exists() + assert not Path(other_session_file).exists() new_session_mapset_list = ( gs.read_command("g.mapsets", flags="l", env=xy_session.env).strip().split(",") ) assert sorted(original_session_mapset_list) == sorted(new_session_mapset_list) - assert os.path.exists(session_file) + assert Path(session_file).exists() assert xy_session.env["GISRC"] @@ -58,16 +58,16 @@ def test_without_context_manager(xy_session): other_session_file = session.env["GISRC"] assert session_file != other_session_file - assert os.path.exists(other_session_file) + assert Path(other_session_file).exists() mapset_path = session.mapset_path - assert os.path.exists(session.mapset_path) + assert Path(session.mapset_path).exists() session.finish() assert not session.active - assert not os.path.exists(mapset_path) - assert not os.path.exists(other_session_file) - assert os.path.exists(session_file) + assert not Path(mapset_path).exists() + assert not Path(other_session_file).exists() + assert Path(session_file).exists() assert xy_session.env["GISRC"] @@ -90,13 +90,13 @@ def test_multiple_sequential_with_context_manager(xy_session): other_session_file = session.env["GISRC"] assert session_file != other_session_file - assert os.path.exists(other_session_file) + assert Path(other_session_file).exists() mapset_path = session.mapset_path - assert os.path.exists(session.mapset_path) + assert Path(session.mapset_path).exists() assert not session.active - assert not os.path.exists(mapset_path) - assert not os.path.exists(other_session_file) - assert os.path.exists(session_file) + assert not Path(mapset_path).exists() + assert not Path(other_session_file).exists() + assert Path(session_file).exists() assert xy_session.env["GISRC"] @@ -118,17 +118,17 @@ def test_multiple_parallel_without_context_manager(xy_session): other_session_file = session.env["GISRC"] assert session_file != other_session_file - assert os.path.exists(other_session_file) - assert os.path.exists(session.mapset_path) + assert Path(other_session_file).exists() + assert Path(session.mapset_path).exists() sessions.append(session) for session in sessions: session.finish() assert not session.active - assert not os.path.exists(session.mapset_path) - assert not os.path.exists(session.env["GISRC"]) + assert not Path(session.mapset_path).exists() + assert not Path(session.env["GISRC"]).exists() - assert os.path.exists(session_file) + assert Path(session_file).exists() assert xy_session.env["GISRC"] @@ -152,13 +152,13 @@ def test_nested_top_env(xy_session): assert top_level_mapset != session_mapset session_file = session.env["GISRC"] assert top_level_session_file != session_file - assert os.path.exists(session_file) - assert os.path.exists(session.mapset_path) + assert Path(session_file).exists() + assert Path(session.mapset_path).exists() for session in [session1, session2, session3]: assert not session.active - assert not os.path.exists(session.mapset_path) - assert not os.path.exists(session.env["GISRC"]) - assert os.path.exists(top_level_session_file) + assert not Path(session.mapset_path).exists() + assert not Path(session.env["GISRC"]).exists() + assert Path(top_level_session_file).exists() def test_nested_inherited_env(xy_session): @@ -181,10 +181,10 @@ def test_nested_inherited_env(xy_session): assert top_level_mapset != session_mapset session_file = session.env["GISRC"] assert top_level_session_file != session_file - assert os.path.exists(session_file) - assert os.path.exists(session.mapset_path) + assert Path(session_file).exists() + assert Path(session.mapset_path).exists() for session in [session1, session2, session3]: assert not session.active - assert not os.path.exists(session.mapset_path) - assert not os.path.exists(session.env["GISRC"]) - assert os.path.exists(top_level_session_file) + assert not Path(session.mapset_path).exists() + assert not Path(session.env["GISRC"]).exists() + assert Path(top_level_session_file).exists() diff --git a/python/grass/grassdb/checks.py b/python/grass/grassdb/checks.py index dd750d1c179..b2e7367fd75 100644 --- a/python/grass/grassdb/checks.py +++ b/python/grass/grassdb/checks.py @@ -221,7 +221,7 @@ def get_reason_id_mapset_not_usable(mapset_path): If mapset path is None or no reason found, returns None. """ # Check whether mapset exists - if not os.path.exists(mapset_path): + if not Path(mapset_path).exists(): return "non-existent" # Check whether mapset is valid if not is_mapset_valid(mapset_path): diff --git a/python/grass/gunittest/invoker.py b/python/grass/gunittest/invoker.py index bf94ec1185e..4d498c892a9 100644 --- a/python/grass/gunittest/invoker.py +++ b/python/grass/gunittest/invoker.py @@ -46,7 +46,7 @@ # TODO: this might be more extend then update def update_keyval_file(filename, module, returncode): - if os.path.exists(filename): + if Path(filename).exists(): keyval = text_to_keyvalue(Path(filename).read_text(encoding="utf-8"), sep="=") else: keyval = {} @@ -145,7 +145,7 @@ def _run_test_module( self.testsuite_dirs[module.tested_dir].append(module.name) cwd: str = os.path.join(results_dir, module.tested_dir, module.name) data_dir: str = os.path.join(module.file_dir, "data") - if os.path.exists(data_dir): + if Path(data_dir).exists(): # TODO: link dir instead of copy tree and remove link afterwads # (removing is good because of testsuite dir in samplecode) # TODO: use different dir name in samplecode and test if it works diff --git a/python/grass/gunittest/main.py b/python/grass/gunittest/main.py index 7cd64cfa24f..cbeba21a738 100644 --- a/python/grass/gunittest/main.py +++ b/python/grass/gunittest/main.py @@ -232,9 +232,9 @@ def main(): if not gisdbase: return "GISDBASE (grassdata directory) cannot be empty string\n" - if not os.path.exists(gisdbase): + if not Path(gisdbase).exists(): return f"GISDBASE (grassdata directory) <{gisdbase}> does not exist\n" - if not os.path.exists(os.path.join(gisdbase, location)): + if not Path(gisdbase, location).exists(): return ( f"GRASS Location <{location}>" f" does not exist in GRASS Database <{gisdbase}>\n" diff --git a/python/grass/gunittest/multireport.py b/python/grass/gunittest/multireport.py index 19a5533febc..58558228864 100644 --- a/python/grass/gunittest/multireport.py +++ b/python/grass/gunittest/multireport.py @@ -499,7 +499,7 @@ def main(): for report in reports: try: summary_file = os.path.join(report, "test_keyvalue_result.txt") - if not os.path.exists(summary_file): + if not Path(summary_file).exists(): sys.stderr.write( "WARNING: Key-value summary not available in" " report <%s>, skipping.\n" % summary_file diff --git a/python/grass/gunittest/utils.py b/python/grass/gunittest/utils.py index 3fce4bb3299..bb2cf9e42b3 100644 --- a/python/grass/gunittest/utils.py +++ b/python/grass/gunittest/utils.py @@ -26,7 +26,7 @@ def ensure_dir(directory: StrOrBytesPath) -> None: """Create all directories in the given path if needed.""" - if not os.path.exists(directory): + if not Path(directory).exists(): os.makedirs(directory) diff --git a/python/grass/jupyter/map.py b/python/grass/jupyter/map.py index b3afe67f96c..6f5fb570d60 100644 --- a/python/grass/jupyter/map.py +++ b/python/grass/jupyter/map.py @@ -17,6 +17,7 @@ import shutil import tempfile import weakref +from pathlib import Path from grass.tools import Tools from grass.tools.support import ToolFunctionResolver @@ -120,7 +121,7 @@ def cleanup(tmpdir): if filename: self._filename = filename - if not read_file and os.path.exists(self._filename): + if not read_file and Path(self._filename).exists(): os.remove(self._filename) else: self._filename = os.path.join(self._tmpdir.name, "map.png") diff --git a/python/grass/jupyter/tests/grass_jupyter_session_test.py b/python/grass/jupyter/tests/grass_jupyter_session_test.py index ebcfa9efbce..9de2be08a6a 100644 --- a/python/grass/jupyter/tests/grass_jupyter_session_test.py +++ b/python/grass/jupyter/tests/grass_jupyter_session_test.py @@ -3,6 +3,7 @@ import subprocess import os import sys +from pathlib import Path # All init tests change the global environment, but we use a separate process @@ -39,7 +40,7 @@ def test_init_finish(tmp_path): assert session_file, "Expected something from the subprocess" session_file = session_file.strip() assert "\n" not in session_file, "Expected a file name from the subprocess" - assert not os.path.exists(session_file), f"Session file {session_file} not deleted" + assert not Path(session_file).exists(), f"Session file {session_file} not deleted" def test_init_with_auto_finish(tmp_path): @@ -60,4 +61,4 @@ def test_init_with_auto_finish(tmp_path): assert session_file, "Expected something from the subprocess" session_file = session_file.strip() assert "\n" not in session_file, "Expected a file name from the subprocess" - assert not os.path.exists(session_file), f"Session file {session_file} not deleted" + assert not Path(session_file).exists(), f"Session file {session_file} not deleted" diff --git a/python/grass/pygrass/vector/__init__.py b/python/grass/pygrass/vector/__init__.py index c447cdac474..9ec34d41427 100644 --- a/python/grass/pygrass/vector/__init__.py +++ b/python/grass/pygrass/vector/__init__.py @@ -1,4 +1,5 @@ -from os.path import join, exists +from os.path import join +from pathlib import Path import grass.lib.gis as libgis import ctypes @@ -248,7 +249,7 @@ def has_color_table(self): """ loc = Location() path = join(loc.path(), self.mapset, "vector", self.name, "colr") - return bool(exists(path)) + return bool(Path(path).exists()) # ============================================= diff --git a/python/grass/pygrass/vector/table.py b/python/grass/pygrass/vector/table.py index 96157a8032b..e5bf8837912 100644 --- a/python/grass/pygrass/vector/table.py +++ b/python/grass/pygrass/vector/table.py @@ -7,6 +7,7 @@ import ctypes import os from collections import OrderedDict +from pathlib import Path import numpy as np from sqlite3 import OperationalError @@ -846,7 +847,7 @@ def connection(self): sqlite3.register_adapter(t, int) dbpath = get_path(self.database, self.table_name) dbdirpath = os.path.split(dbpath)[0] - if not os.path.exists(dbdirpath): + if not Path(dbdirpath).exists(): os.mkdir(dbdirpath) return sqlite3.connect(dbpath) if driver == "pg": diff --git a/python/grass/script/core.py b/python/grass/script/core.py index 10ed0a43c1c..335f121d325 100644 --- a/python/grass/script/core.py +++ b/python/grass/script/core.py @@ -223,7 +223,7 @@ def get_commands(*, env=None): def scan(gisbase, directory): dir_path = os.path.join(gisbase, directory) - if os.path.exists(dir_path): + if Path(dir_path).exists(): for fname in os.listdir(os.path.join(gisbase, directory)): if scripts: # win32 name, ext = os.path.splitext(fname) @@ -1986,7 +1986,7 @@ def create_project( mapset_path = resolve_mapset_path(path=path, location=name) # create dbase if not exists - if not os.path.exists(mapset_path.directory): + if not Path(mapset_path.directory).exists(): os.mkdir(mapset_path.directory) env = None diff --git a/python/grass/script/tests/grass_script_create_project_pack_test.py b/python/grass/script/tests/grass_script_create_project_pack_test.py index de6f063bd8e..b5dc97adc51 100644 --- a/python/grass/script/tests/grass_script_create_project_pack_test.py +++ b/python/grass/script/tests/grass_script_create_project_pack_test.py @@ -3,6 +3,8 @@ import shutil import os +from pathlib import Path + import pytest import grass.script as gs @@ -35,9 +37,9 @@ def test_raster_pack_crs_param_extensions(tmp_path, pack_raster_file4x5_rows, su def test_raster_pack_file(tmp_path, pack_raster_file4x5_rows): project = tmp_path / "test" gs.create_project(project, pack=pack_raster_file4x5_rows) - assert os.path.exists(project) + assert project.exists() for name in ["PROJ_INFO", "PROJ_UNITS", "PROJ_SRID"]: - assert os.path.exists(project / "PERMANENT" / name) + assert Path(project, "PERMANENT", name).exists() @pytest.mark.parametrize("compression", ["c", None]) diff --git a/python/grass/script/tests/grass_script_setup_test.py b/python/grass/script/tests/grass_script_setup_test.py index ec1cc6cc491..93a58605dac 100644 --- a/python/grass/script/tests/grass_script_setup_test.py +++ b/python/grass/script/tests/grass_script_setup_test.py @@ -68,8 +68,8 @@ def test_init_as_context_manager(tmp_path): with gs.setup.init(project, env=os.environ.copy()) as session: gs.run_command("g.region", flags="p", env=session.env) session_file = session.env["GISRC"] - assert os.path.exists(session_file) - assert not os.path.exists(session_file) + assert Path(session_file).exists() + assert not Path(session_file).exists() @pytest.mark.usefixtures("mock_no_session") @@ -86,7 +86,7 @@ def test_init_session_finish(tmp_path): with pytest.raises(ValueError, match="finished session"): session.finish() assert not session.active - assert not os.path.exists(session_file) + assert not Path(session_file).exists() @pytest.mark.usefixtures("mock_no_session") @@ -100,7 +100,7 @@ def test_global_finish_session_only_in_env(tmp_path): session.finish() # Test preconditions assert not session.active - assert not os.path.exists(session_file) + assert not Path(session_file).exists() # The global function can only know that a session does not exist, # but not that it existed but has been finished. # On top of that, without capured stderr, the error message has @@ -120,7 +120,7 @@ def test_init_finish_global_functions_with_env(tmp_path): session_file = env["GISRC"] gs.setup.finish(env=env) - assert not os.path.exists(session_file) + assert not Path(session_file).exists() @pytest.mark.parametrize("capture_stderr", [True, False, None]) @@ -160,7 +160,7 @@ def test_init_finish_global_functions_capture_strerr(tmp_path, capture_stderr): assert result["session_file"], "Expected file name from the subprocess" assert result["runtime_present"], RUNTIME_GISBASE_SHOULD_BE_PRESENT assert result["gisbase_exists"], "Install directory should exist" - assert not os.path.exists(result["session_file"]), SESSION_FILE_NOT_DELETED + assert not Path(result["session_file"]).exists(), SESSION_FILE_NOT_DELETED assert result["crs_type"] == "xy" @@ -197,7 +197,7 @@ def test_init_finish_global_functions_runtime_persists(tmp_path): result = run_in_subprocess(code, tmp_path=tmp_path) assert result["session_file"], "Expected file name from the subprocess" assert result["runtime_present"], RUNTIME_GISBASE_SHOULD_BE_PRESENT - assert not os.path.exists(result["session_file"]), SESSION_FILE_NOT_DELETED + assert not Path(result["session_file"]).exists(), SESSION_FILE_NOT_DELETED # This is testing the current implementation behavior, but it is not required # to be this way in terms of design. assert result["runtime_present_after"], "Runtime should continue to be present" @@ -258,7 +258,7 @@ def test_init_finish_global_functions_set_environment(tmp_path): assert not result["session_file_variable_present_after"], ( "Not expecting GISRC when finished" ) - assert not os.path.exists(result["session_file"]), SESSION_FILE_NOT_DELETED + assert not Path(result["session_file"]).exists(), SESSION_FILE_NOT_DELETED @pytest.mark.usefixtures("mock_no_session") @@ -289,7 +289,7 @@ def test_init_as_context_manager_env_attribute(tmp_path): assert result["session_file"], "Expected file name from the subprocess" assert result["file_existed"], "File should have been present" assert result["runtime_present"], RUNTIME_GISBASE_SHOULD_BE_PRESENT - assert not os.path.exists(result["session_file"]), SESSION_FILE_NOT_DELETED + assert not Path(result["session_file"]).exists(), SESSION_FILE_NOT_DELETED assert not os.environ.get("GISRC") assert not os.environ.get("GISBASE") assert result["region_data"]["crs"]["type"] == "xy" diff --git a/python/grass/script/utils.py b/python/grass/script/utils.py index 51df6befc1f..232b1286de2 100644 --- a/python/grass/script/utils.py +++ b/python/grass/script/utils.py @@ -535,7 +535,7 @@ def set_path(modulename, dirname=None, path="."): pathlib_ = None if dirname: pathlib_ = os.path.join(path, dirname) - if pathlib_ and os.path.exists(pathlib_): + if pathlib_ and Path(pathlib_).exists(): # we are running the script from the script directory, therefore # we add the path to sys.path to reach the directory (dirname) sys.path.append(os.path.abspath(path)) diff --git a/python/grass/temporal/core.py b/python/grass/temporal/core.py index e1641f0fe9c..a70742e1f0b 100644 --- a/python/grass/temporal/core.py +++ b/python/grass/temporal/core.py @@ -504,13 +504,13 @@ def get_available_temporal_mapsets(): # mapset # to create it if ( - driver == "sqlite" and os.path.exists(database) + driver == "sqlite" and Path(database).exists() ) or mapset == get_current_mapset(): tgis_mapsets[mapset] = (driver, database) # We need to warn if the connection is defined but the database does not # exists - if driver == "sqlite" and not os.path.exists(database): + if driver == "sqlite" and not Path(database).exists(): message_interface.warning( "Temporal database connection defined as:\n" + database @@ -689,7 +689,7 @@ def init(raise_fatal_error: bool = False, skip_db_version_check: bool = False): # Check if the database already exists if tgis_backend == "sqlite": # Check path of the sqlite database - if os.path.exists(tgis_database_string): + if Path(tgis_database_string).exists(): dbif.connect() # Check for raster_base table dbif.execute( @@ -877,7 +877,7 @@ def create_temporal_database(dbif) -> None: if tgis_backend == "sqlite": # We need to create the sqlite3 database path if it does not exist tgis_dir = os.path.dirname(tgis_database_string) - if not os.path.exists(tgis_dir): + if not Path(tgis_dir).exists(): try: os.makedirs(tgis_dir) except Exception as e: diff --git a/python/grass/temporal/stds_import.py b/python/grass/temporal/stds_import.py index 183baba2423..5e995a29cd3 100644 --- a/python/grass/temporal/stds_import.py +++ b/python/grass/temporal/stds_import.py @@ -260,9 +260,9 @@ def import_stds( gs.set_raise_on_error(True) # Check if input file and extraction directory exits - if not os.path.exists(input): + if not Path(input).exists(): gs.fatal(_("Space time raster dataset archive <%s> not found") % input) - if not create and not os.path.exists(directory): + if not create and not Path(directory).exists(): gs.fatal(_("Extraction directory <%s> not found") % directory) tar = tarfile.open(name=input, mode="r") @@ -481,7 +481,7 @@ def import_stds( if format_ == "GTiff": for row in maplist: filename = row["filename"] + ".tif" - if not os.path.exists(filename): + if not Path(filename).exists(): gs.fatal( _("Unable to find GeoTIFF raster file <%s> in archive.") % filename @@ -489,7 +489,7 @@ def import_stds( elif format_ == "AAIGrid": for row in maplist: filename = row["filename"] + ".asc" - if not os.path.exists(filename): + if not Path(filename).exists(): gs.fatal( _("Unable to find AAIGrid raster file <%s> in archive.") % filename @@ -497,7 +497,7 @@ def import_stds( elif format_ == "GML": for row in maplist: filename = row["filename"] + ".xml" - if not os.path.exists(filename): + if not Path(filename).exists(): gs.fatal( _("Unable to find GML vector file <%s> in archive.") % filename ) @@ -507,7 +507,7 @@ def import_stds( filename = str(row["filename"].split(":")[0]) + ".pack" else: filename = row["filename"] + ".pack" - if not os.path.exists(filename): + if not Path(filename).exists(): gs.fatal( _("Unable to find GRASS package file <%s> in archive.") % filename diff --git a/python/grass/tools/tests/conftest.py b/python/grass/tools/tests/conftest.py index ae1edd1f76c..accf8339cbc 100644 --- a/python/grass/tools/tests/conftest.py +++ b/python/grass/tools/tests/conftest.py @@ -1,5 +1,6 @@ """Fixtures for grass.tools""" +from __future__ import annotations import os import pytest @@ -7,10 +8,14 @@ import grass.script as gs from grass.tools import Tools from grass.tools.support import ToolResult, ToolFunctionResolver +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from pathlib import Path @pytest.fixture -def xy_dataset_session(tmp_path): +def xy_dataset_session(tmp_path: Path): """Creates a session with XY project""" gs.create_project(tmp_path / "test") with gs.setup.init(tmp_path / "test", env=os.environ.copy()) as session: @@ -18,7 +23,9 @@ def xy_dataset_session(tmp_path): @pytest.fixture(scope="module") -def xy_dataset_session_for_module(tmp_path_factory): +def xy_dataset_session_for_module( + tmp_path_factory: pytest.TempPathFactory, +): """Creates a session with XY project""" tmp_path = tmp_path_factory.mktemp("module_project") gs.create_project(tmp_path / "test") @@ -52,7 +59,7 @@ def echoing_resolver(): @pytest.fixture(scope="module") -def rows_raster_file3x2(tmp_path_factory): +def rows_raster_file3x2(tmp_path_factory: pytest.TempPathFactory) -> Path: """Native raster pack file Smallest possible file, but with rows and columns greater than one, @@ -77,7 +84,7 @@ def rows_raster_file3x2(tmp_path_factory): @pytest.fixture(scope="module") -def rows_raster_file4x5(tmp_path_factory): +def rows_raster_file4x5(tmp_path_factory: pytest.TempPathFactory) -> Path: """Native raster pack file Small file, but slightly larger than the smallest. @@ -101,7 +108,7 @@ def rows_raster_file4x5(tmp_path_factory): @pytest.fixture(scope="module") -def ones_raster_file_epsg3358(tmp_path_factory): +def ones_raster_file_epsg3358(tmp_path_factory: pytest.TempPathFactory) -> Path: """Native raster pack with EPSG:3358""" tmp_path = tmp_path_factory.mktemp("ones_raster_file4x5") project = tmp_path / "xy_test4x5" @@ -122,7 +129,7 @@ def ones_raster_file_epsg3358(tmp_path_factory): @pytest.fixture(scope="module") -def ones_raster_file_epsg4326(tmp_path_factory): +def ones_raster_file_epsg4326(tmp_path_factory: pytest.TempPathFactory) -> Path: """Native raster pack with EPSG:4326 (LL)""" tmp_path = tmp_path_factory.mktemp("ones_raster_file4x5") project = tmp_path / "xy_test4x5" diff --git a/python/grass/tools/tests/grass_tools_session_tools_pack_test.py b/python/grass/tools/tests/grass_tools_session_tools_pack_test.py index e1f7ef209ef..ac037e52132 100644 --- a/python/grass/tools/tests/grass_tools_session_tools_pack_test.py +++ b/python/grass/tools/tests/grass_tools_session_tools_pack_test.py @@ -11,12 +11,12 @@ def test_pack_input_output_tool_name_function( - xy_dataset_session, rows_raster_file3x2, tmp_path + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path ): """Check input and output pack files work with tool name call""" tools = Tools(session=xy_dataset_session) tools.g_region(rows=3, cols=3) - assert os.path.exists(rows_raster_file3x2) + assert rows_raster_file3x2.exists() output_file = tmp_path / "file.grass_raster" tools.r_slope_aspect(elevation=rows_raster_file3x2, slope=output_file) assert output_file.exists() @@ -29,7 +29,7 @@ def test_pack_input_output_tool_name_function( @pytest.mark.parametrize("parameter_type", [str, Path]) def test_pack_input_output_tool_name_function_string_value( - xy_dataset_session, rows_raster_file3x2, tmp_path, parameter_type + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path, parameter_type ): """Check input and output pack files work string a parameter @@ -38,7 +38,7 @@ def test_pack_input_output_tool_name_function_string_value( """ tools = Tools(session=xy_dataset_session) tools.g_region(rows=3, cols=3) - assert os.path.exists(rows_raster_file3x2) + assert rows_raster_file3x2.exists() output_file = tmp_path / "file.grass_raster" tools.r_slope_aspect( elevation=parameter_type(rows_raster_file3x2), slope=parameter_type(output_file) @@ -52,12 +52,12 @@ def test_pack_input_output_tool_name_function_string_value( def test_pack_input_output_with_name_and_parameter_call( - xy_dataset_session, rows_raster_file3x2, tmp_path + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path ): """Check input and output pack files work with tool name as string""" tools = Tools(session=xy_dataset_session) tools.g_region(rows=3, cols=3) - assert os.path.exists(rows_raster_file3x2) + assert rows_raster_file3x2.exists() output_file = tmp_path / "file.grass_raster" tools.run("r.slope.aspect", elevation=rows_raster_file3x2, slope=output_file) assert output_file.exists() @@ -69,11 +69,11 @@ def test_pack_input_output_with_name_and_parameter_call( def test_pack_input_output_with_subprocess_run_like_call( - xy_dataset_session, rows_raster_file3x2, tmp_path + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path ): """Check input and output pack files work with command as list""" tools = Tools(session=xy_dataset_session) - assert os.path.exists(rows_raster_file3x2) + assert rows_raster_file3x2.exists() output_file = tmp_path / "file.grass_raster" tools.run_cmd( [ @@ -340,11 +340,13 @@ def test_repeated_output(xy_dataset_session, rows_raster_file3x2, tmp_path): assert output_file.exists() -def test_output_without_overwrite(xy_dataset_session, rows_raster_file3x2, tmp_path): +def test_output_without_overwrite( + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path +): """Check input and output pack files work with tool name call""" tools = Tools(session=xy_dataset_session) tools.g_region(rows=3, cols=3) - assert os.path.exists(rows_raster_file3x2) + assert rows_raster_file3x2.exists() output_file = tmp_path / "file.grass_raster" tools.r_slope_aspect(elevation=rows_raster_file3x2, slope=output_file) with pytest.raises(ToolError, match=r"[Oo]verwrite"): @@ -353,12 +355,12 @@ def test_output_without_overwrite(xy_dataset_session, rows_raster_file3x2, tmp_p def test_output_with_object_level_overwrite( - xy_dataset_session, rows_raster_file3x2, tmp_path + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path ): """Check input and output pack files work with tool name call""" tools = Tools(session=xy_dataset_session, overwrite=True) tools.g_region(rows=3, cols=3) - assert os.path.exists(rows_raster_file3x2) + assert rows_raster_file3x2.exists() output_file = tmp_path / "file.grass_raster" tools.r_slope_aspect(elevation=rows_raster_file3x2, slope=output_file) # Same call the second time. @@ -367,12 +369,12 @@ def test_output_with_object_level_overwrite( def test_output_with_function_level_overwrite( - xy_dataset_session, rows_raster_file3x2, tmp_path + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path ): """Check input and output pack files work with tool name call""" tools = Tools(session=xy_dataset_session) tools.g_region(rows=3, cols=3) - assert os.path.exists(rows_raster_file3x2) + assert rows_raster_file3x2.exists() output_file = tmp_path / "file.grass_raster" tools.r_slope_aspect(elevation=rows_raster_file3x2, slope=output_file) # Same call the second time. @@ -382,7 +384,7 @@ def test_output_with_function_level_overwrite( assert output_file.exists() -def test_non_existent_pack_input(xy_dataset_session, tmp_path): +def test_non_existent_pack_input(xy_dataset_session, tmp_path: Path): """Check input and output pack files work with tool name call""" tools = Tools(session=xy_dataset_session) tools.g_region(rows=3, cols=3) @@ -400,7 +402,7 @@ def test_non_existent_pack_input(xy_dataset_session, tmp_path): def test_non_existent_output_pack_directory( - xy_dataset_session, rows_raster_file3x2, tmp_path + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path ): """Check input and output pack files work with tool name call""" tools = Tools(session=xy_dataset_session) @@ -416,7 +418,7 @@ def test_non_existent_output_pack_directory( tools.r_slope_aspect(elevation=rows_raster_file3x2, slope=output_file) -def test_wrong_parameter(xy_dataset_session, rows_raster_file3x2, tmp_path): +def test_wrong_parameter(xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path): """Check wrong parameter causes standard exception Since the tool is called to process its parameters with pack IO, @@ -432,7 +434,7 @@ def test_wrong_parameter(xy_dataset_session, rows_raster_file3x2, tmp_path): ) -def test_direct_r_unpack_to_data(xy_dataset_session, rows_raster_file3x2): +def test_direct_r_unpack_to_data(xy_dataset_session, rows_raster_file3x2: Path): """Check that we can r.unpack data as usual""" tools = Tools(session=xy_dataset_session, use_cache=True) tools.g_region(rows=3, cols=3) @@ -444,7 +446,9 @@ def test_direct_r_unpack_to_data(xy_dataset_session, rows_raster_file3x2): )["name"] -def test_direct_r_unpack_to_pack(xy_dataset_session, rows_raster_file3x2, tmp_path): +def test_direct_r_unpack_to_pack( + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path +): """Check that roundtrip from existing packed raster to new packed raster works""" tools = Tools(session=xy_dataset_session, use_cache=True) tools.g_region(rows=3, cols=3) @@ -460,7 +464,7 @@ def test_direct_r_unpack_to_pack(xy_dataset_session, rows_raster_file3x2, tmp_pa )["name"] -def test_direct_r_pack_from_data(xy_dataset_session, tmp_path): +def test_direct_r_pack_from_data(xy_dataset_session, tmp_path: Path): """Check that we can r.pack data as usual""" tools = Tools(session=xy_dataset_session, use_cache=True) tools.g_region(rows=3, cols=3) @@ -481,7 +485,9 @@ def test_direct_r_pack_from_data(xy_dataset_session, tmp_path): assert tools.g_findfile(element="raster", file="data_1", format="json")["name"] -def test_direct_r_pack_from_pack(xy_dataset_session, rows_raster_file3x2, tmp_path): +def test_direct_r_pack_from_pack( + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path +): """Check that roundtrip from existing packed raster to raster works""" tools = Tools(session=xy_dataset_session, use_cache=True) tools.g_region(rows=3, cols=3) @@ -508,7 +514,7 @@ def test_direct_r_pack_from_pack(xy_dataset_session, rows_raster_file3x2, tmp_pa def test_clean_after_tool_failure_with_context_and_try( - xy_dataset_session, rows_raster_file3x2, tmp_path + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path ): """Check we delete imported input when we fail after that import. @@ -531,7 +537,7 @@ def test_clean_after_tool_failure_with_context_and_try( def test_clean_after_tool_failure_with_context_and_raises( - xy_dataset_session, rows_raster_file3x2, tmp_path + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path ): """Check input and output pack files work with tool name call @@ -552,7 +558,7 @@ def test_clean_after_tool_failure_with_context_and_raises( def test_clean_after_tool_failure_without_context( - xy_dataset_session, rows_raster_file3x2, tmp_path + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path ): """Check we delete imported input when we fail after that import. @@ -570,7 +576,7 @@ def test_clean_after_tool_failure_without_context( def test_clean_after_tool_failure_without_context_with_use_cache( - xy_dataset_session, rows_raster_file3x2, tmp_path + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path ): """Check we don't delete imported input even after failure when asked. @@ -593,7 +599,7 @@ def test_clean_after_tool_failure_without_context_with_use_cache( def test_clean_after_call_failure_with_context_and_try( - xy_dataset_session, rows_raster_file3x2, tmp_path + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path ): """Check we delete imported input when we fail after that import. @@ -621,7 +627,7 @@ def test_clean_after_call_failure_with_context_and_try( def test_clean_after_call_failure_with_context_and_raises( - xy_dataset_session, rows_raster_file3x2, tmp_path + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path ): """Check input and output pack files work with tool name call @@ -644,7 +650,7 @@ def test_clean_after_call_failure_with_context_and_raises( def test_clean_after_call_failure_without_context( - xy_dataset_session, rows_raster_file3x2, tmp_path + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path ): """Check we delete imported input when we fail after that import. @@ -666,7 +672,7 @@ def test_clean_after_call_failure_without_context( def test_clean_after_call_failure_without_context_with_use_cache( - xy_dataset_session, rows_raster_file3x2, tmp_path + xy_dataset_session, rows_raster_file3x2: Path, tmp_path: Path ): """Check we don't delete imported input even after failure when asked. @@ -693,7 +699,7 @@ def test_clean_after_call_failure_without_context_with_use_cache( def test_workflow_create_project_and_run_general_crs( - tmp_path, ones_raster_file_epsg3358 + tmp_path: Path, ones_raster_file_epsg3358 ): """Check workflow with create project""" project = tmp_path / "project" @@ -720,7 +726,9 @@ def test_workflow_create_project_and_run_general_crs( assert raster.is_file() -def test_workflow_create_project_and_run_ll_crs(tmp_path, ones_raster_file_epsg4326): +def test_workflow_create_project_and_run_ll_crs( + tmp_path: Path, ones_raster_file_epsg4326 +): """Check workflow with create project""" project = tmp_path / "project" raster = tmp_path / "raster.grass_raster" @@ -746,7 +754,9 @@ def test_workflow_create_project_and_run_ll_crs(tmp_path, ones_raster_file_epsg4 assert raster.is_file() -def test_workflow_create_project_and_run_xy_crs(tmp_path, rows_raster_file4x5): +def test_workflow_create_project_and_run_xy_crs( + tmp_path: Path, rows_raster_file4x5: Path +): """Check workflow with create project""" project = tmp_path / "project" raster = tmp_path / "raster.grass_raster" diff --git a/python/grass/utils/download.py b/python/grass/utils/download.py index ade1ac9411c..b54a30ce607 100644 --- a/python/grass/utils/download.py +++ b/python/grass/utils/download.py @@ -132,7 +132,7 @@ def _move_extracted_files(extract_dir, target_dir, files): else: shutil.copy(actual_path, target_dir) else: - if not os.path.exists(target_dir): + if not Path(target_dir).exists(): os.mkdir(target_dir) for file_name in files: actual_file = os.path.join(extract_dir, file_name) diff --git a/raster/r.in.pdal/testsuite/test_r_in_pdal_binning.py b/raster/r.in.pdal/testsuite/test_r_in_pdal_binning.py index c256224590d..2fdef1aa66e 100644 --- a/raster/r.in.pdal/testsuite/test_r_in_pdal_binning.py +++ b/raster/r.in.pdal/testsuite/test_r_in_pdal_binning.py @@ -10,9 +10,9 @@ """ import os -import pathlib import unittest import shutil +from pathlib import Path from tempfile import TemporaryDirectory from grass.script import core as grass @@ -34,7 +34,7 @@ def setUpClass(cls): cls.use_temp_region() cls.runModule("g.region", n=18, s=0, e=18, w=0, res=6) - cls.data_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "data") + cls.data_dir = os.path.join(Path(__file__).parent.absolute(), "data") cls.point_file = os.path.join(cls.data_dir, "points.csv") cls.tmp_dir = TemporaryDirectory() cls.las_file = os.path.join(cls.tmp_dir.name, "points.las") diff --git a/raster/r.in.pdal/testsuite/test_r_in_pdal_print.py b/raster/r.in.pdal/testsuite/test_r_in_pdal_print.py index 2c613ab88e2..e3d21b47c2b 100644 --- a/raster/r.in.pdal/testsuite/test_r_in_pdal_print.py +++ b/raster/r.in.pdal/testsuite/test_r_in_pdal_print.py @@ -11,9 +11,9 @@ """ import os -import pathlib import shutil import unittest +from pathlib import Path from tempfile import TemporaryDirectory from grass.script import core as grass @@ -36,7 +36,7 @@ def setUpClass(cls): cls.use_temp_region() cls.runModule("g.region", n=18, s=0, e=18, w=0, res=6) - cls.data_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "data") + cls.data_dir = os.path.join(Path(__file__).parent.absolute(), "data") cls.point_file = os.path.join(cls.data_dir, "points.csv") cls.tmp_dir = TemporaryDirectory() cls.las_file = os.path.join(cls.tmp_dir.name, "points.las") @@ -58,7 +58,7 @@ def setUpClass(cls): ] ) cls.broken_las = os.path.join(cls.tmp_dir.name, "broken.las") - pathlib.Path(cls.broken_las).write_bytes(b"LASF") + Path(cls.broken_las).write_bytes(b"LASF") @classmethod def tearDownClass(cls): diff --git a/raster/r.in.pdal/testsuite/test_r_in_pdal_selection.py b/raster/r.in.pdal/testsuite/test_r_in_pdal_selection.py index 4796702d2f6..3c521eacb23 100644 --- a/raster/r.in.pdal/testsuite/test_r_in_pdal_selection.py +++ b/raster/r.in.pdal/testsuite/test_r_in_pdal_selection.py @@ -10,9 +10,9 @@ """ import os -import pathlib import shutil import unittest +from pathlib import Path from tempfile import TemporaryDirectory from grass.script import core as grass @@ -34,7 +34,7 @@ def setUpClass(cls): cls.use_temp_region() cls.runModule("g.region", n=18, s=0, e=18, w=0, res=6) - cls.data_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "data") + cls.data_dir = os.path.join(Path(__file__).parent.absolute(), "data") cls.point_file = os.path.join(cls.data_dir, "points.csv") cls.tmp_dir = TemporaryDirectory() cls.las_file = os.path.join(cls.tmp_dir.name, "points.las") diff --git a/raster/r.kappa/testsuite/test_r_kappa.py b/raster/r.kappa/testsuite/test_r_kappa.py index ff11f477925..7716f3bb42d 100644 --- a/raster/r.kappa/testsuite/test_r_kappa.py +++ b/raster/r.kappa/testsuite/test_r_kappa.py @@ -10,9 +10,8 @@ """ import os -import pathlib import json - +from pathlib import Path from tempfile import NamedTemporaryFile from grass.script import read_command @@ -33,7 +32,7 @@ def setUpClass(cls): cls.use_temp_region() cls.runModule("g.region", n=5, s=0, e=5, w=0, res=1) - cls.data_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "data") + cls.data_dir = os.path.join(Path(__file__).parent.absolute(), "data") cls.ref_1 = tempname(10) cls.runModule( "r.in.ascii", @@ -90,7 +89,7 @@ def setUpClass(cls): cls.use_temp_region() cls.runModule("g.region", n=5, s=0, e=5, w=0, res=1) - cls.data_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "data") + cls.data_dir = os.path.join(Path(__file__).parent.absolute(), "data") cls.ref_1 = tempname(10) cls.runModule( "r.in.ascii", @@ -205,7 +204,7 @@ def setUpClass(cls): cls.use_temp_region() cls.runModule("g.region", n=5, s=0, e=5, w=0, res=1) - cls.data_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "data") + cls.data_dir = os.path.join(Path(__file__).parent.absolute(), "data") cls.ref_1 = tempname(10) cls.runModule( "r.in.ascii", @@ -308,7 +307,7 @@ def setUpClass(cls): cls.use_temp_region() cls.runModule("g.region", n=5, s=0, e=5, w=0, res=1) - cls.data_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "data") + cls.data_dir = os.path.join(Path(__file__).parent.absolute(), "data") cls.references = [] cls.classifications = [] cls.expected_outputs = [] diff --git a/raster/r.smooth.edgepreserve/testsuite/test_r_smooth_edgepreserve.py b/raster/r.smooth.edgepreserve/testsuite/test_r_smooth_edgepreserve.py index 824dd6ae89c..28b061c8ab4 100644 --- a/raster/r.smooth.edgepreserve/testsuite/test_r_smooth_edgepreserve.py +++ b/raster/r.smooth.edgepreserve/testsuite/test_r_smooth_edgepreserve.py @@ -10,7 +10,7 @@ """ import os -import pathlib +from pathlib import Path from grass.script.core import tempname from grass.script.raster import raster_info @@ -31,7 +31,7 @@ def setUpClass(cls): cls.use_temp_region() cls.runModule("g.region", n=10, s=0, e=10, w=0, res=1) - cls.data_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "data") + cls.data_dir = os.path.join(Path(__file__).parent.absolute(), "data") cls.rm_rast = [] cls.in_map_i = tempname(10) diff --git a/raster/r.terraflow/testsuite/test_r_terraflow.py b/raster/r.terraflow/testsuite/test_r_terraflow.py index 4085151a337..4c2329cde3c 100644 --- a/raster/r.terraflow/testsuite/test_r_terraflow.py +++ b/raster/r.terraflow/testsuite/test_r_terraflow.py @@ -4,6 +4,7 @@ import os import tempfile +from pathlib import Path from grass.gunittest.case import TestCase @@ -25,7 +26,7 @@ def tearDownClass(cls): def setUp(self): """Create input data for steady state groundwater flow computation""" - if not os.path.exists(self.testdir): + if not Path(self.testdir).exists(): os.mkdir(self.testdir) def test_univar_mfd(self): diff --git a/scripts/d.polar/d.polar.py b/scripts/d.polar/d.polar.py index 2d5f6d50a7b..b3d705f602c 100755 --- a/scripts/d.polar/d.polar.py +++ b/scripts/d.polar/d.polar.py @@ -48,6 +48,7 @@ import atexit import glob import shutil +from pathlib import Path from grass.script.utils import try_remove, basename from grass.script import core as gcore @@ -421,7 +422,7 @@ def main(): gcore.fatal(_("Please select only one output method")) if eps: - if os.sep in eps and not os.path.exists(os.path.dirname(eps)): + if os.sep in eps and not Path(eps).parent.exists(): gcore.fatal( _( "EPS output file path <{}>, doesn't exists. " @@ -432,7 +433,7 @@ def main(): eps = basename(eps, "eps") + ".eps" if not eps.endswith(".eps"): eps += ".eps" - if os.path.exists(eps) and not os.getenv("GRASS_OVERWRITE"): + if Path(eps).exists() and not os.getenv("GRASS_OVERWRITE"): gcore.fatal( _( "option : <{}> exists. To overwrite, " diff --git a/scripts/db.out.ogr/db.out.ogr.py b/scripts/db.out.ogr/db.out.ogr.py index 4fe5b4f9854..200f31fb99a 100755 --- a/scripts/db.out.ogr/db.out.ogr.py +++ b/scripts/db.out.ogr/db.out.ogr.py @@ -56,6 +56,7 @@ # %end import os +from pathlib import Path from grass.script.utils import try_remove, basename from grass.script import core as gcore @@ -75,7 +76,7 @@ def main(): # is there a simpler way of testing for --overwrite? dbffile = input + ".dbf" - if os.path.exists(dbffile) and not gcore.overwrite(): + if Path(dbffile).exists() and not gcore.overwrite(): gcore.fatal(_("File <%s> already exists") % dbffile) if olayer: diff --git a/scripts/g.extension.all/g.extension.all.py b/scripts/g.extension.all/g.extension.all.py index ea926be6ef7..8ac6d47a85a 100644 --- a/scripts/g.extension.all/g.extension.all.py +++ b/scripts/g.extension.all/g.extension.all.py @@ -42,7 +42,7 @@ import sys import xml.etree.ElementTree as ET - +from pathlib import Path from urllib import request as urlrequest from urllib.error import HTTPError, URLError @@ -60,7 +60,7 @@ def get_extensions(): if not addon_base: gs.fatal(_("%s not defined") % "GRASS_ADDON_BASE") fXML = os.path.join(addon_base, "modules.xml") - if not os.path.exists(fXML): + if not Path(fXML).exists(): return [] # read XML file diff --git a/scripts/g.extension/g.extension.py b/scripts/g.extension/g.extension.py index 66cb2a9deb7..1f66baf3994 100644 --- a/scripts/g.extension/g.extension.py +++ b/scripts/g.extension/g.extension.py @@ -669,7 +669,7 @@ def get_installed_toolboxes(force=False): to read the current one. """ xml_file = os.path.join(options["prefix"], "toolboxes.xml") - if not os.path.exists(xml_file): + if not Path(xml_file).exists(): write_xml_toolboxes(xml_file) # read XML file try: @@ -692,7 +692,7 @@ def get_installed_modules(force=False): to read the current one. """ xml_file = os.path.join(options["prefix"], "modules.xml") - if not os.path.exists(xml_file): + if not Path(xml_file).exists(): if force: write_xml_modules(xml_file) else: @@ -1282,7 +1282,7 @@ def install_toolbox_xml(url, name): xml_file = os.path.join(options["prefix"], "toolboxes.xml") # create an empty file if not exists - if not os.path.exists(xml_file): + if not Path(xml_file).exists(): write_xml_modules(xml_file) # read XML file @@ -1382,7 +1382,7 @@ def install_extension_xml(edict): xml_file = os.path.join(options["prefix"], "extensions.xml") # create an empty file if not exists - if not os.path.exists(xml_file): + if not Path(xml_file).exists(): write_xml_extensions(xml_file) # read XML file @@ -1502,7 +1502,7 @@ def install_module_xml(mlist): xml_file = os.path.join(options["prefix"], "modules.xml") # create an empty file if not exists - if not os.path.exists(xml_file): + if not Path(xml_file).exists(): write_xml_modules(xml_file) # read XML file @@ -1748,7 +1748,7 @@ def move_extracted_files(extract_dir, target_dir, files): if len(files) == 1: shutil.copytree(os.path.join(extract_dir, files[0]), target_dir) else: - if not os.path.exists(target_dir): + if not Path(target_dir).exists(): os.mkdir(target_dir) for file_name in files: actual_file = os.path.join(extract_dir, file_name) @@ -1964,7 +1964,7 @@ def create_md_if_missing(root_dir): md_file = os.path.splitext(html_file)[0] + ".md" md_path = os.path.join(dirpath, md_file) - if not os.path.exists(md_path): + if not Path(md_path).exists(): html_path = os.path.join(dirpath, html_file) shutil.copy(html_path, md_path) @@ -2078,7 +2078,7 @@ def install_extension_std_platforms(name, source, url, branch): os.chdir(srcdir) gs.message(_("Compiling...")) - if not os.path.exists(os.path.join(gisbase, "include", "Make", "Module.make")): + if not Path(gisbase, "include", "Make", "Module.make").exists(): gs.fatal(_("Please install GRASS development package")) if gs.call(make_cmd, stdout=outdev) != 0: @@ -2126,7 +2126,7 @@ def remove_extension(force=False): # collect modules and files installed by these extensions mlist = [] xml_file = os.path.join(options["prefix"], "extensions.xml") - if os.path.exists(xml_file): + if Path(xml_file).exists(): # read XML file tree = None try: @@ -2157,7 +2157,7 @@ def remove_extension(force=False): write_xml_extensions(xml_file) xml_file = os.path.join(options["prefix"], "modules.xml") - if not os.path.exists(xml_file): + if not Path(xml_file).exists(): if force: write_xml_modules(xml_file) else: @@ -2227,7 +2227,7 @@ def remove_extension_files(edict, force=False): einstalled = [] eremoved = [] - if os.path.exists(xml_file): + if Path(xml_file).exists(): tree = etree_fromfile(xml_file) if tree is not None: for task in tree.findall("task"): @@ -2296,7 +2296,7 @@ def remove_extension_std(name, force=False): def remove_from_toolbox_xml(name): """Update local meta-file when removing existing toolbox""" xml_file = os.path.join(options["prefix"], "toolboxes.xml") - if not os.path.exists(xml_file): + if not Path(xml_file).exists(): return # read XML file tree = etree_fromfile(xml_file) @@ -2316,7 +2316,7 @@ def remove_extension_xml(mlist, edict): # modules xml_file = os.path.join(options["prefix"], "modules.xml") - if os.path.exists(xml_file): + if Path(xml_file).exists(): # read XML file tree = etree_fromfile(xml_file) for name in mlist: @@ -2328,7 +2328,7 @@ def remove_extension_xml(mlist, edict): # extensions xml_file = os.path.join(options["prefix"], "extensions.xml") - if os.path.exists(xml_file): + if Path(xml_file).exists(): # read XML file tree = etree_fromfile(xml_file) for name in edict: @@ -2483,7 +2483,7 @@ def resolve_install_prefix(path, to_system): ) else: path = os.environ["GRASS_ADDON_BASE"] - if os.path.exists(path) and not os.access(path, os.W_OK): + if Path(path).exists() and not os.access(path, os.W_OK): gs.fatal( _( "You don't have permission to install extension to <{0}>." @@ -2606,7 +2606,7 @@ def resolve_known_host_service(url, name, branch): def validate_url(url): - if not os.path.exists(url): + if not Path(url).exists(): url_validated = False message = None if url.startswith("http"): @@ -2725,7 +2725,7 @@ def resolve_source_code(url=None, name=None, branch=None, fork=False): # Handle local URLs if os.path.isdir(url): return "dir", os.path.abspath(url) - if os.path.exists(url): + if Path(url).exists(): if url.endswith(".zip"): return "zip", os.path.abspath(url) for suffix in extract_tar.supported_formats: diff --git a/scripts/g.extension/testsuite/test_addons_modules.py b/scripts/g.extension/testsuite/test_addons_modules.py index 7d18b1f45d2..8ee21dd7784 100644 --- a/scripts/g.extension/testsuite/test_addons_modules.py +++ b/scripts/g.extension/testsuite/test_addons_modules.py @@ -76,7 +76,7 @@ class TestModulesFromDifferentSources(TestCase): def setUp(self): """Make sure we are not dealing with some old files""" - if os.path.exists(self.install_prefix): + if Path(self.install_prefix).exists(): files = [p.name for p in Path(self.install_prefix).iterdir()] if files: msg = "Install prefix path '{}' contains files {}".format( diff --git a/scripts/g.manual/g.manual.py b/scripts/g.manual/g.manual.py index ca73b3caa40..58e93aea870 100755 --- a/scripts/g.manual/g.manual.py +++ b/scripts/g.manual/g.manual.py @@ -48,6 +48,7 @@ import sys import os +from pathlib import Path from urllib.request import urlopen import webbrowser @@ -79,20 +80,20 @@ def start_browser(entry): ) else: directory = os.path.join(gisbase, "docs", "mkdocs", "site") - if os.path.exists(directory): + if Path(directory).exists(): path = os.path.join(directory, entry + ".html") - if not os.path.exists(path) and os.getenv("GRASS_ADDON_BASE"): + if not Path(path).exists() and os.getenv("GRASS_ADDON_BASE"): path = os.path.join( os.getenv("GRASS_ADDON_BASE"), "docs", "html", entry + ".html" ) else: path = os.path.join(gisbase, "docs", "html", entry + ".html") - if not os.path.exists(path) and os.getenv("GRASS_ADDON_BASE"): + if not Path(path).exists() and os.getenv("GRASS_ADDON_BASE"): path = os.path.join( os.getenv("GRASS_ADDON_BASE"), "docs", "html", entry + ".html" ) - if not os.path.exists(path): + if not Path(path).exists(): grass.fatal(_("No HTML manual page entry for '%s'") % entry) url_path = "file://" + path @@ -116,13 +117,13 @@ def start_browser(entry): def start_man(entry): path = os.path.join(gisbase, "docs", "man", "man1", entry + ".1") - if not os.path.exists(path) and os.getenv("GRASS_ADDON_BASE"): + if not Path(path).exists() and os.getenv("GRASS_ADDON_BASE"): path = os.path.join( os.getenv("GRASS_ADDON_BASE"), "docs", "man", "man1", entry + ".1" ) for ext in ["", ".gz", ".bz2"]: - if os.path.exists(path + ext): + if Path(path + ext).exists(): os.execlp("man", "man", path + ext) grass.fatal(_("Error starting 'man' for '%s'") % path) grass.fatal(_("No manual page entry for '%s'") % entry) diff --git a/scripts/i.oif/testsuite/test_i_oif.py b/scripts/i.oif/testsuite/test_i_oif.py index c6efea14957..313f96853bb 100644 --- a/scripts/i.oif/testsuite/test_i_oif.py +++ b/scripts/i.oif/testsuite/test_i_oif.py @@ -36,7 +36,7 @@ def setUpClass(cls): @classmethod def tearDownClass(cls): """Clean up the test environment by removing created maps and files.""" - if os.path.exists(cls.output_file): + if Path(cls.output_file).exists(): os.remove(cls.output_file) cls.runModule( @@ -125,7 +125,7 @@ def test_output_to_file(self): ) self.assertTrue( - os.path.exists(self.output_file), msg="Output file was not created." + Path(self.output_file).exists(), msg="Output file was not created." ) content = Path(self.output_file).read_text() diff --git a/scripts/m.proj/m.proj.py b/scripts/m.proj/m.proj.py index d41c36cfcd4..d2c5c3411fa 100755 --- a/scripts/m.proj/m.proj.py +++ b/scripts/m.proj/m.proj.py @@ -99,8 +99,8 @@ # %end import sys -import os import threading +from pathlib import Path from grass.script.utils import separator, parse_key_val, encode, decode from grass.script import core as gcore @@ -221,7 +221,7 @@ def main(): inf = sys.stdin else: infile = input - if not os.path.exists(infile): + if not Path(infile).exists(): gcore.fatal(_("Unable to read input data")) inf = open(infile) gcore.debug("input file=[%s]" % infile) diff --git a/scripts/r.import/r.import.py b/scripts/r.import/r.import.py index 1b84c2ae33c..14c13902c82 100644 --- a/scripts/r.import/r.import.py +++ b/scripts/r.import/r.import.py @@ -118,6 +118,8 @@ import atexit import math +from pathlib import Path + import grass.script as gs from grass.exceptions import CalledModuleError @@ -303,10 +305,10 @@ def main(): # is output a group? group = False path = os.path.join(GISDBASE, TMPLOC, "group", output) - if os.path.exists(path): + if Path(path).exists(): group = True path = os.path.join(GISDBASE, TMPLOC, "group", output, "POINTS") - if os.path.exists(path): + if Path(path).exists(): gs.fatal(_("Input contains GCPs, rectification is required")) if "r" in region_flag: diff --git a/scripts/r.in.wms/wms_cap_parsers.py b/scripts/r.in.wms/wms_cap_parsers.py index c54ede9f49e..bab43fd9df0 100644 --- a/scripts/r.in.wms/wms_cap_parsers.py +++ b/scripts/r.in.wms/wms_cap_parsers.py @@ -17,7 +17,7 @@ @author Stepan Turek (Mentor: Martin Landa) """ -import pathlib +from pathlib import Path from xml.etree.ElementTree import ParseError @@ -30,7 +30,7 @@ def __init__(self, cap_file): """!Initialize xml.etree.ElementTree""" is_file = False try: - xml = pathlib.Path(cap_file) + xml = Path(cap_file) if xml.exists(): is_file = True except OSError as exc: diff --git a/scripts/r.pack/r.pack.py b/scripts/r.pack/r.pack.py index 1b041ec8f7d..0b3c32a9a09 100644 --- a/scripts/r.pack/r.pack.py +++ b/scripts/r.pack/r.pack.py @@ -74,7 +74,7 @@ def main(): grass.fatal(_("Raster map <%s> not found") % infile) parent_dir = Path(outfile).parent - if os.path.exists(outfile): + if os.path.exists(outfile): # noqa: PTH110 # Problem with tests, the way a permission error occurs when checking if os.getenv("GRASS_OVERWRITE"): grass.warning( _("Pack file <%s> already exists and will be overwritten") % outfile @@ -103,7 +103,7 @@ def main(): ) if map_file["file"]: vrt = os.path.join(map_file["file"], "vrt") - if os.path.exists(vrt): + if Path(vrt).exists(): with open(vrt) as f: for r in f: map, mapset = r.split("@") @@ -124,7 +124,7 @@ def main(): "hist", ]: path = os.path.join(basedir, element, infile) - if os.path.exists(path): + if Path(path).exists(): grass.debug("copying %s" % path) if os.path.isfile(path): shutil.copyfile( @@ -141,10 +141,10 @@ def main(): if vrt_files: for f, value in vrt_files.items(): f_tmp_dir = os.path.join(tmp, f) - if not os.path.exists(f_tmp_dir): + if not Path(f_tmp_dir).exists(): os.mkdir(f_tmp_dir) path = os.path.join(value, element, f) - if os.path.exists(path): + if Path(path).exists(): grass.debug("copying vrt file {}".format(path)) if os.path.isfile(path): shutil.copyfile( @@ -167,7 +167,7 @@ def main(): path = os.path.join( gisenv["GISDBASE"], gisenv["LOCATION_NAME"], "PERMANENT", "PROJ_" + support ) - if os.path.exists(path): + if Path(path).exists(): shutil.copyfile(path, os.path.join(tmp_dir, "PROJ_" + support)) # copy CRS info from computational region diff --git a/scripts/r.pack/tests/r_pack_test.py b/scripts/r.pack/tests/r_pack_test.py index a1016ea7b41..d5f104d5e9e 100644 --- a/scripts/r.pack/tests/r_pack_test.py +++ b/scripts/r.pack/tests/r_pack_test.py @@ -108,7 +108,7 @@ def test_output_dir_is_not_writable(xy_raster_dataset_session_for_module, tmp_pa parent.chmod(stat.S_IREAD) output = parent / "output_1.rpack" # Calling output.exists() gives permission denied on Linux, but os.path does not. - assert not os.path.exists(output) + assert not os.path.exists(output) # noqa: PTH110 assert output.parent.exists() assert output.parent.is_dir() with pytest.raises( diff --git a/scripts/r.unpack/r.unpack.py b/scripts/r.unpack/r.unpack.py index 5be7ec037ac..7c5963594d8 100644 --- a/scripts/r.unpack/r.unpack.py +++ b/scripts/r.unpack/r.unpack.py @@ -62,7 +62,7 @@ def main(): tmp_dir = grass.tempdir() grass.debug("tmp_dir = {tmpdir}".format(tmpdir=tmp_dir)) - if not os.path.exists(infile): + if not Path(infile).exists(): grass.fatal(_("File {name} not found.").format(name=infile)) gisenv = grass.gisenv() @@ -121,9 +121,9 @@ def main(): tar.close() os.chdir(data_names[0]) - if os.path.exists("cell"): + if Path("cell").exists(): pass - elif os.path.exists("coor"): + elif Path("coor").exists(): grass.fatal( _( "This GRASS pack file contains vector data. Use " @@ -146,8 +146,8 @@ def main(): proj_info_file_2 = os.path.join(mset_dir, "..", "PERMANENT", "PROJ_INFO") skip_projection_check = False - if not os.path.exists(proj_info_file_1): - if os.path.exists(proj_info_file_2): + if not Path(proj_info_file_1).exists(): + if Path(proj_info_file_2).exists(): grass.fatal( _( "PROJ_INFO file is missing, unpack raster map in XY " @@ -203,11 +203,11 @@ def main(): for element in ["cats", "cell", "cellhd", "cell_misc", "colr", "fcell", "hist"]: src_path = os.path.join(tmp_dir, data, element) - if not os.path.exists(src_path): + if not Path(src_path).exists(): continue path = os.path.join(mset_dir, element) - if not os.path.exists(path): + if not Path(path).exists(): os.mkdir(path) if element == "cell_misc": @@ -227,7 +227,7 @@ def main(): if index == 0: vrt_file = os.path.join(path, "vrt") - if os.path.exists(path): + if Path(path).exists(): shutil.rmtree(path) shutil.copytree(src_path, path) else: @@ -238,7 +238,7 @@ def main(): # Update vrt file if maps: - if vrt_file and os.path.exists(vrt_file): + if vrt_file and Path(vrt_file).exists(): files = "\n".join(maps) Path(vrt_file).write_text(files) diff --git a/scripts/r3.in.xyz/r3.in.xyz.py b/scripts/r3.in.xyz/r3.in.xyz.py index 5b2c8be4a65..84d27990fae 100755 --- a/scripts/r3.in.xyz/r3.in.xyz.py +++ b/scripts/r3.in.xyz/r3.in.xyz.py @@ -171,6 +171,7 @@ import sys import os import atexit +from pathlib import Path from grass.script import core as grass from grass.exceptions import CalledModuleError @@ -208,7 +209,7 @@ def main(): if workers == 1 and "WORKERS" in os.environ: workers = int(os.environ["WORKERS"]) - if not os.path.exists(infile): + if not Path(infile).exists(): grass.fatal(_("Unable to read input file <%s>") % infile) addl_opts = {} diff --git a/scripts/v.in.e00/v.in.e00.py b/scripts/v.in.e00/v.in.e00.py index 4258fa3181a..ead5015fe3f 100755 --- a/scripts/v.in.e00/v.in.e00.py +++ b/scripts/v.in.e00/v.in.e00.py @@ -41,6 +41,7 @@ import os import shutil import glob +from pathlib import Path from grass.script.utils import try_rmdir, try_remove, basename from grass.script import vector as gvect from grass.script import core as gcore @@ -80,7 +81,7 @@ def main(): # check if this is a split E00 file (.e01, .e02 ...): merging = False - if os.path.exists(e00name + ".e01") or os.path.exists(e00name + ".E01"): + if Path(e00name + ".e01").exists() or Path(e00name + ".E01").exists(): gcore.message( _("Found that E00 file is split into pieces (.e01, ...). Merging...") ) diff --git a/scripts/v.in.lines/v.in.lines.py b/scripts/v.in.lines/v.in.lines.py index 2105626a07f..b2cdf112bac 100755 --- a/scripts/v.in.lines/v.in.lines.py +++ b/scripts/v.in.lines/v.in.lines.py @@ -35,8 +35,8 @@ # %end import sys -import os import atexit +from pathlib import Path from grass.script.utils import separator, try_remove from grass.script import core as grass @@ -59,7 +59,7 @@ def main(): inf = sys.stdin else: infile = options["input"] - if not os.path.exists(infile): + if not Path(infile).exists(): grass.fatal(_("Unable to read input file <%s>") % infile) grass.debug("input file=[%s]" % infile) diff --git a/scripts/v.in.wfs/v.in.wfs.py b/scripts/v.in.wfs/v.in.wfs.py index c112e2070bf..b9fe74ee6f6 100755 --- a/scripts/v.in.wfs/v.in.wfs.py +++ b/scripts/v.in.wfs/v.in.wfs.py @@ -206,7 +206,7 @@ def main(): if flags["l"]: import shutil - if os.path.exists("wms_capabilities.xml"): + if Path("wms_capabilities.xml").exists(): grass.fatal(_('A file called "wms_capabilities.xml" already exists here')) # os.move() might fail if the temp file is on another volume, so we copy instead shutil.copy(tmpxml, "wms_capabilities.xml") diff --git a/scripts/v.pack/v.pack.py b/scripts/v.pack/v.pack.py index 5e3e962e580..bfb7e78af74 100755 --- a/scripts/v.pack/v.pack.py +++ b/scripts/v.pack/v.pack.py @@ -76,7 +76,7 @@ def main(): outfile = options["output"] or infile + ".pack" # check if exists the output file - if os.path.exists(outfile): + if Path(outfile).exists(): if os.getenv("GRASS_OVERWRITE"): grass.warning( _("Pack file <%s> already exists and will be overwritten") % outfile @@ -127,7 +127,7 @@ def main(): path = os.path.join( gisenv["GISDBASE"], gisenv["LOCATION_NAME"], "PERMANENT", "PROJ_" + support ) - if os.path.exists(path): + if Path(path).exists(): tar.add(path, "PROJ_" + support) tar.close() diff --git a/scripts/v.unpack/v.unpack.py b/scripts/v.unpack/v.unpack.py index 75b32a46a1d..29ad4803685 100644 --- a/scripts/v.unpack/v.unpack.py +++ b/scripts/v.unpack/v.unpack.py @@ -47,6 +47,7 @@ import shutil import tarfile import atexit +from pathlib import Path from grass.script.utils import diff_files, try_rmdir from grass.script import core as grass @@ -67,7 +68,7 @@ def main(): grass.debug("tmp_dir = %s" % tmp_dir) # check if the input file exists - if not os.path.exists(infile): + if not Path(infile).exists(): grass.fatal(_("File <%s> not found") % infile) # copy the files to tmp dir @@ -130,9 +131,9 @@ def main(): grass.warning(_("Extracting may be unsafe; consider updating Python")) tar.extractall() tar.close() - if os.path.exists(os.path.join(data_name, "coor")): + if Path(data_name, "coor").exists(): pass - elif os.path.exists(os.path.join(data_name, "cell")): + elif Path(data_name, "cell").exists(): grass.fatal( _("This GRASS pack file contains raster data. Use r.unpack to unpack <%s>") % map_name @@ -145,8 +146,8 @@ def main(): loc_proj_units = os.path.join(mset_dir, "..", "PERMANENT", "PROJ_UNITS") skip_projection_check = False - if not os.path.exists(os.path.join(tmp_dir, "PROJ_INFO")): - if os.path.exists(loc_proj): + if not Path(tmp_dir, "PROJ_INFO").exists(): + if Path(loc_proj).exists(): grass.fatal( _( "PROJ_INFO file is missing, unpack vector map in XY (unprojected) " @@ -206,7 +207,7 @@ def main(): # copy file shutil.copytree(data_name, new_dir) # exist fromdb - if os.path.exists(fromdb): + if Path(fromdb).exists(): # the db connection in the output mapset dbconn = grassdb.db_connection(force=True) todb = dbconn["database"] @@ -216,13 +217,9 @@ def main(): dbnlist = dbln.readlines() dbln.close() # check if dbf or sqlite directory exists - if dbconn["driver"] == "dbf" and not os.path.exists( - os.path.join(mset_dir, "dbf") - ): + if dbconn["driver"] == "dbf" and not Path(mset_dir, "dbf").exists(): os.mkdir(os.path.join(mset_dir, "dbf")) - elif dbconn["driver"] == "sqlite" and not os.path.exists( - os.path.join(mset_dir, "sqlite") - ): + elif dbconn["driver"] == "sqlite" and not Path(mset_dir, "sqlite").exists(): os.mkdir(os.path.join(mset_dir, "sqlite")) # for each old connection for t in dbnlist: diff --git a/temporal/t.rast.export/t.rast.export.py b/temporal/t.rast.export/t.rast.export.py index 48e0960ae25..21e3e1d285b 100755 --- a/temporal/t.rast.export/t.rast.export.py +++ b/temporal/t.rast.export/t.rast.export.py @@ -105,6 +105,7 @@ # %end import os +from pathlib import Path import grass.script as gs @@ -126,7 +127,7 @@ def main(): key: options[key] for key in ("createopt", "metaopt", "nodata") if options[key] } - if not directory or not os.path.exists(directory): + if not directory or not Path(directory).exists(): gs.fatal(_("Directory {} not found").format(directory)) if not os.access(directory, os.W_OK): diff --git a/temporal/t.rast.out.vtk/t.rast.out.vtk.py b/temporal/t.rast.out.vtk/t.rast.out.vtk.py index 876770e4c4e..b9ae8f4e803 100755 --- a/temporal/t.rast.out.vtk/t.rast.out.vtk.py +++ b/temporal/t.rast.out.vtk/t.rast.out.vtk.py @@ -73,6 +73,7 @@ # %end import os +from pathlib import Path import grass.script as gs from grass.exceptions import CalledModuleError @@ -97,7 +98,7 @@ def main(): # Make sure the temporal database exists tgis.init() - if not os.path.exists(expdir): + if not Path(expdir).exists(): gs.fatal(_("Export directory <%s> not found.") % expdir) os.chdir(expdir) diff --git a/utils/create_python_init_file.py b/utils/create_python_init_file.py index 8d045b9924b..d60d3134914 100755 --- a/utils/create_python_init_file.py +++ b/utils/create_python_init_file.py @@ -17,10 +17,11 @@ import os import sys import glob +from pathlib import Path def main(path): - if not os.path.exists(path) or not os.path.isdir(path): + if not Path(path).exists() or not Path(path).is_dir(): print("'{}' is not a directory".format(path), file=sys.stderr) return 1 diff --git a/utils/merge_sitemaps.py b/utils/merge_sitemaps.py index 8652eb37f44..4d3f01af30f 100644 --- a/utils/merge_sitemaps.py +++ b/utils/merge_sitemaps.py @@ -6,7 +6,6 @@ @author: Corey White """ -import os import argparse from xml.dom import minidom # noqa: S408 import urllib.parse @@ -96,7 +95,7 @@ def main(): # Check arguments args = parser.parse_args() mkdocs_sitemap = args.mkdocs_sitemap - if not os.path.exists(mkdocs_sitemap): + if not Path(mkdocs_sitemap).exists(): error_message = "MKDocs sitemap.xml does not exist" raise FileNotFoundError(error_message) diff --git a/utils/mkdocs.py b/utils/mkdocs.py index d031bfb3700..e0a32297c41 100644 --- a/utils/mkdocs.py +++ b/utils/mkdocs.py @@ -276,7 +276,7 @@ def get_git_commit_from_file( top_dir, "core_modules_with_last_commit.json", ) - if os.path.exists(json_file_path): + if Path(json_file_path).exists(): with open(json_file_path) as f: core_modules_with_last_commit = json.load(f) if pgm in core_modules_with_last_commit: diff --git a/utils/mkhtml.py b/utils/mkhtml.py index 890ecf5de04..b476e22eba7 100644 --- a/utils/mkhtml.py +++ b/utils/mkhtml.py @@ -26,6 +26,7 @@ from html.parser import HTMLParser import urllib.parse as urlparse +from pathlib import Path try: import grass.script as gs @@ -471,7 +472,7 @@ def to_title(name): addon_path = get_addon_path(base_url=base_url, pgm=pgm, major_version=major) if addon_path: # Addon is installed from the local dir - if os.path.exists(os.getenv("SOURCE_URL")): + if Path(os.getenv("SOURCE_URL")).exists(): url_source = urlparse.urljoin( addons_url, addon_path, diff --git a/utils/mkmarkdown.py b/utils/mkmarkdown.py index 40edb5424d1..17a2b898815 100644 --- a/utils/mkmarkdown.py +++ b/utils/mkmarkdown.py @@ -21,6 +21,7 @@ import string import re import urllib.parse as urlparse +from pathlib import Path try: import grass.script as gs @@ -80,7 +81,7 @@ def parse_source(pgm): addon_path = get_addon_path(base_url=base_url, pgm=pgm, major_version=major) if addon_path: # Addon is installed from the local dir - if os.path.exists(os.getenv("SOURCE_URL")): + if Path(os.getenv("SOURCE_URL")).exists(): url_source = urlparse.urljoin( addons_url, addon_path, diff --git a/utils/test_generate_last_commit_file.py b/utils/test_generate_last_commit_file.py index e6218b9cc4f..d5566767a92 100644 --- a/utils/test_generate_last_commit_file.py +++ b/utils/test_generate_last_commit_file.py @@ -22,6 +22,7 @@ import subprocess import pytest +from pathlib import Path from .generate_last_commit_file import COMMIT_DATE_FORMAT @@ -38,7 +39,7 @@ def read_json_file(json_file): def test_json_file_exists(json_file): - assert os.path.exists(json_file) is True + assert Path(json_file).exists() is True @pytest.mark.depends(on=["test_json_file_exists"]) diff --git a/utils/thumbnails.py b/utils/thumbnails.py index c04c806bb13..12115b428b5 100755 --- a/utils/thumbnails.py +++ b/utils/thumbnails.py @@ -161,7 +161,7 @@ def main(): color_dir = os.path.join(os.environ["GISBASE"], "etc", "colors") output_dir = sys.argv[1] - if not os.path.exists(output_dir): + if not Path(output_dir).exists(): os.makedirs(output_dir) pid = os.getpid()