diff --git a/AutoDuck/fixHelpCompression.py b/AutoDuck/fixHelpCompression.py index de4008e722..593de44825 100644 --- a/AutoDuck/fixHelpCompression.py +++ b/AutoDuck/fixHelpCompression.py @@ -7,10 +7,8 @@ fname = sys.argv[1] -try: - os.stat(fname) -except OSError: - sys.stderr.write("The project file '%s' was not found\n" % (fname)) +if not os.path.exists(fname): + sys.stderr.write(f"The project file '{fname}' was not found\n") sys.exit(1) win32api.WriteProfileVal("options", "COMPRESS", "12 Hall Zeck", fname) diff --git a/Pythonwin/pywin/Demos/hiertest.py b/Pythonwin/pywin/Demos/hiertest.py index a22dc3b946..763d658efb 100644 --- a/Pythonwin/pywin/Demos/hiertest.py +++ b/Pythonwin/pywin/Demos/hiertest.py @@ -101,12 +101,9 @@ def __init__(self, filename): def GetText(self): try: - return "%-20s %d bytes" % ( - os.path.basename(self.filename), - os.stat(self.filename)[6], - ) + return f"{os.path.basename(self.filename):<20} {os.stat(self.filename)[6]} bytes" except OSError as details: - return "%-20s - %s" % (self.filename, details[1]) + return f"{self.filename:<20} - {details[1]}" def IsExpandable(self): return os.path.isdir(self.filename) diff --git a/Pythonwin/pywin/framework/scriptutils.py b/Pythonwin/pywin/framework/scriptutils.py index abf5a40c13..6bcb5ef119 100644 --- a/Pythonwin/pywin/framework/scriptutils.py +++ b/Pythonwin/pywin/framework/scriptutils.py @@ -284,10 +284,9 @@ def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None): # If no path specified, try and locate the file path, fnameonly = os.path.split(script) if len(path) == 0: - try: - os.stat(fnameonly) # See if it is OK as is... + if os.path.exists(fnameonly): # See if it is OK as is... script = fnameonly - except OSError: + else: fullScript = LocatePythonFile(script) if fullScript is None: win32ui.MessageBox("The file '%s' can not be located" % script) @@ -637,9 +636,7 @@ def FindTabNanny(): print(" The file '%s' can not be located" % (filename)) return None fname = os.path.join(path, "Tools\\Scripts\\%s" % filename) - try: - os.stat(fname) - except OSError: + if not os.path.exists(fname): print(f"WARNING - The file '{filename}' can not be located in path '{path}'") return None diff --git a/com/win32com/client/gencache.py b/com/win32com/client/gencache.py index 4012cb2a58..59f5c8d124 100644 --- a/com/win32com/client/gencache.py +++ b/com/win32com/client/gencache.py @@ -168,15 +168,9 @@ def GetGeneratePath(): Checks the directory is OK. """ assert not is_readonly, "Why do you want the genpath for a readonly store?" - try: - os.makedirs(win32com.__gen_path__) - # os.mkdir(win32com.__gen_path__) - except OSError: - pass - try: - fname = os.path.join(win32com.__gen_path__, "__init__.py") - os.stat(fname) - except OSError: + os.makedirs(win32com.__gen_path__, exist_ok=True) + fname = os.path.join(win32com.__gen_path__, "__init__.py") + if not os.path.exists(fname): f = open(fname, "w") f.write( "# Generated file - this directory may be deleted to reset the COM cache...\n" diff --git a/com/win32com/server/register.py b/com/win32com/server/register.py index 8a05ea117f..f68f6781a2 100644 --- a/com/win32com/server/register.py +++ b/com/win32com/server/register.py @@ -133,18 +133,14 @@ def _find_localserver_module(): path = next(iter(win32com.server.__path__)) baseName = "localserver" pyfile = os.path.join(path, baseName + ".py") - try: - os.stat(pyfile) - except OSError: + if not os.path.exists(pyfile): # See if we have a compiled extension if __debug__: ext = ".pyc" else: ext = ".pyo" pyfile = os.path.join(path, baseName + ext) - try: - os.stat(pyfile) - except OSError: + if not os.path.exists(pyfile): raise RuntimeError( "Can not locate the Python module 'win32com.server.%s'" % baseName ) diff --git a/com/win32com/test/GenTestScripts.py b/com/win32com/test/GenTestScripts.py index 8b09df0771..85770295c1 100644 --- a/com/win32com/test/GenTestScripts.py +++ b/com/win32com/test/GenTestScripts.py @@ -28,10 +28,7 @@ def GetGenPath(): def GenerateFromRegistered(fname, *loadArgs): # tlb = apply(pythoncom.LoadRegTypeLib, loadArgs) genPath = GetGenPath() - try: - os.stat(genPath) - except OSError: - os.mkdir(genPath) + os.makedirs(genPath, exist_ok=True) # Ensure an __init__ exists. open(os.path.join(genPath, "__init__.py"), "w").close() print(fname, ": generating -", end=" ") diff --git a/com/win32comext/shell/demos/servers/column_provider.py b/com/win32comext/shell/demos/servers/column_provider.py index 092f99ff86..8bfd67134a 100644 --- a/com/win32comext/shell/demos/servers/column_provider.py +++ b/com/win32comext/shell/demos/servers/column_provider.py @@ -80,8 +80,7 @@ def GetItemData(self, colid, colData): ext = ".pyo" check_file = os.path.splitext(name)[0] + ext try: - st = os.stat(check_file) - return st[stat.ST_SIZE] + return os.stat(check_file)[stat.ST_SIZE] except OSError: # No file return None diff --git a/win32/Lib/regcheck.py b/win32/Lib/regcheck.py index 27aab3e5d6..66103fd785 100644 --- a/win32/Lib/regcheck.py +++ b/win32/Lib/regcheck.py @@ -18,13 +18,15 @@ def CheckRegisteredExe(exename): try: - os.stat( + if os.path.exists( win32api.RegQueryValue( regutil.GetRootKey(), regutil.GetAppPathsKey() + "\\" + exename ) - ) - except (OSError, win32api.error): - print("Registration of %s - Not registered correctly" % exename) + ): + return + except win32api.error: + pass + print(f"Registration of {exename} - Not registered correctly") def CheckPathString(pathString): @@ -110,11 +112,10 @@ def CheckHelpFiles(verbose): if verbose: print("\t" + helpDesc + ":", end=" ") # query the os section. - try: - os.stat(helpFile) + if os.path.exists(helpFile): if verbose: print(helpFile) - except OSError: + else: print("** Help file %s does not exist" % helpFile) keyNo += 1 except win32api.error as exc: diff --git a/win32/Lib/regutil.py b/win32/Lib/regutil.py index 5a72bc7aac..24c227236d 100644 --- a/win32/Lib/regutil.py +++ b/win32/Lib/regutil.py @@ -145,11 +145,7 @@ def RegisterModule(modName, modPath): modName -- The name of the module, as used by import. modPath -- The full path and file name of the module. """ - try: - import os - - os.stat(modPath) - except OSError: + if not os.path.exists(modPath): print("Warning: Registering non-existant module %s" % modPath) win32api.RegSetValue( GetRootKey(), @@ -204,11 +200,9 @@ def RegisterHelpFile(helpFile, helpPath, helpDesc=None, bCheckFile=1): if helpDesc is None: helpDesc = helpFile fullHelpFile = os.path.join(helpPath, helpFile) - try: - if bCheckFile: - os.stat(fullHelpFile) - except OSError: - raise ValueError("Help file does not exist") + if bCheckFile: + if not os.path.exists(fullHelpFile): + raise ValueError("Help file does not exist") # Now register with Python itself. win32api.RegSetValue( GetRootKey(), @@ -264,11 +258,8 @@ def RegisterCoreDLL(coredllName=None): if coredllName is None: coredllName = win32api.GetModuleFileName(sys.dllhandle) # must exist! - else: - try: - os.stat(coredllName) - except OSError: - print("Warning: Registering non-existant core DLL %s" % coredllName) + elif not os.path.exists(coredllName): + print(f"Warning: Registering non-existant core DLL {coredllName}") hKey = win32api.RegCreateKey(GetRootKey(), BuildDefaultPythonKey()) try: diff --git a/win32/scripts/VersionStamp/BrandProject.py b/win32/scripts/VersionStamp/BrandProject.py index 9d3d816dbe..b6e2f118ca 100644 --- a/win32/scripts/VersionStamp/BrandProject.py +++ b/win32/scripts/VersionStamp/BrandProject.py @@ -86,12 +86,10 @@ def usage(msg): usage("You must specify the required arguments") vssProjectName = "$\\" + args[0] descFile = args[1] + if not os.path.exists(descFile): + usage(f"The description file '{descFile}' can not be found") path = args[2] - try: - os.stat(descFile) - except OSError: - usage("The description file '%s' can not be found" % (descFile)) if not os.path.isdir(path): - usage("The path to the files to stamp '%s' does not exist" % (path)) + usage(f"The path to the files to stamp '{path}' does not exist") BrandProject(vssProjectName, descFile, path, stampFiles, desc, bAuto, bRebrand) diff --git a/win32/scripts/backupEventLog.py b/win32/scripts/backupEventLog.py index 2a4ea5024e..7c255e4059 100644 --- a/win32/scripts/backupEventLog.py +++ b/win32/scripts/backupEventLog.py @@ -8,21 +8,15 @@ def BackupClearLog(logType): datePrefix = time.strftime("%Y%m%d", time.localtime(time.time())) - fileExists = 1 retry = 0 - while fileExists: - if retry == 0: - index = "" - else: - index = "-%d" % retry - try: - fname = os.path.join( - win32api.GetTempPath(), - f"{datePrefix}{index}-{logType}" + ".evt", - ) - os.stat(fname) - except OSError: - fileExists = 0 + while True: # file exists + index = "" if retry == 0 else f"-{retry}" + fname = os.path.join( + win32api.GetTempPath(), + f"{datePrefix}{index}-{logType}.evt", + ) + if not os.path.exists(fname): + break retry += 1 # OK - have unique file name. try: diff --git a/win32/scripts/regsetup.py b/win32/scripts/regsetup.py index ca44ed672b..c7814b57df 100644 --- a/win32/scripts/regsetup.py +++ b/win32/scripts/regsetup.py @@ -12,11 +12,7 @@ def FileExists(fname): """Check if a file exists. Returns true or false.""" import os - try: - os.stat(fname) - return 1 - except OSError as details: - return 0 + return os.path.exists(fname) def IsPackageDir(path, packageName, knownFileName): @@ -188,11 +184,10 @@ def LocateFileName(fileNamesString, searchPaths): fileNames = fileNamesString.split(";") for path in searchPaths: for fileName in fileNames: - try: - retPath = os.path.join(path, fileName) - os.stat(retPath) + retPath = os.path.join(path, fileName) + if os.path.exists(retPath): break - except OSError: + else: retPath = None if retPath: break