From bcfd93c8fe056ae5875c792615d567dbf899219e Mon Sep 17 00:00:00 2001 From: Glenn Jocher Date: Fri, 5 Nov 2021 15:34:08 +0100 Subject: [PATCH] Fix `increment_path()` explicit file vs dir handling Resolves https://github.com/ultralytics/yolov5/pull/5341#issuecomment-961774729 Tests: ```python import glob import re from pathlib import Path def increment_path(path, exist_ok=False, sep='', mkdir=False): # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc. path = Path(path) # os-agnostic if path.exists() and not exist_ok: path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '') dirs = glob.glob(f"{path}{sep}*") # similar paths matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs] i = [int(m.groups()[0]) for m in matches if m] # indices n = max(i) + 1 if i else 2 # increment number path = Path(f"{path}{sep}{n}{suffix}") # increment path if mkdir: path.mkdir(parents=True, exist_ok=True) # make directory return path print(increment_path('runs')) print(increment_path('export.py')) print(increment_path('abc.def.dir')) print(increment_path('abc.def.file')) ``` --- utils/general.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/utils/general.py b/utils/general.py index adbf1bd48c5f..fc05c691afa2 100755 --- a/utils/general.py +++ b/utils/general.py @@ -830,13 +830,12 @@ def increment_path(path, exist_ok=False, sep='', mkdir=False): # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc. path = Path(path) # os-agnostic if path.exists() and not exist_ok: - suffix = path.suffix - path = path.with_suffix('') + path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '') dirs = glob.glob(f"{path}{sep}*") # similar paths matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs] i = [int(m.groups()[0]) for m in matches if m] # indices n = max(i) + 1 if i else 2 # increment number - path = Path(f"{path}{sep}{n}{suffix}") # update path + path = Path(f"{path}{sep}{n}{suffix}") # increment path if mkdir: path.mkdir(parents=True, exist_ok=True) # make directory return path