glenn-jocher commited on
Commit
8535053
1 Parent(s): bcc085d

Fix `increment_path()` explicit file vs dir handling (#5523)

Browse files

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'))
```

Files changed (1) hide show
  1. utils/general.py +2 -3
utils/general.py CHANGED
@@ -830,13 +830,12 @@ def increment_path(path, exist_ok=False, sep='', mkdir=False):
830
  # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.
831
  path = Path(path) # os-agnostic
832
  if path.exists() and not exist_ok:
833
- suffix = path.suffix
834
- path = path.with_suffix('')
835
  dirs = glob.glob(f"{path}{sep}*") # similar paths
836
  matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs]
837
  i = [int(m.groups()[0]) for m in matches if m] # indices
838
  n = max(i) + 1 if i else 2 # increment number
839
- path = Path(f"{path}{sep}{n}{suffix}") # update path
840
  if mkdir:
841
  path.mkdir(parents=True, exist_ok=True) # make directory
842
  return path
 
830
  # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.
831
  path = Path(path) # os-agnostic
832
  if path.exists() and not exist_ok:
833
+ path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '')
 
834
  dirs = glob.glob(f"{path}{sep}*") # similar paths
835
  matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs]
836
  i = [int(m.groups()[0]) for m in matches if m] # indices
837
  n = max(i) + 1 if i else 2 # increment number
838
+ path = Path(f"{path}{sep}{n}{suffix}") # increment path
839
  if mkdir:
840
  path.mkdir(parents=True, exist_ok=True) # make directory
841
  return path