glenn-jocher commited on
Commit
1a3ecb8
1 Parent(s): 177da7f

`increment_path()` robustness improvements (#7628)

Browse files

Improved robustness to filename edge cases like `data/images/zidane.23.jpg` that currently fail. May resolve https://github.com/ultralytics/yolov5/issues/7432

Files changed (1) hide show
  1. utils/general.py +16 -5
utils/general.py CHANGED
@@ -933,13 +933,24 @@ def increment_path(path, exist_ok=False, sep='', mkdir=False):
933
  path = Path(path) # os-agnostic
934
  if path.exists() and not exist_ok:
935
  path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '')
936
- dirs = glob.glob(f"{path}{sep}*") # similar paths
937
- matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs]
938
- i = [int(m.groups()[0]) for m in matches if m] # indices
939
- n = max(i) + 1 if i else 2 # increment number
940
- path = Path(f"{path}{sep}{n}{suffix}") # increment path
 
 
 
 
 
 
 
 
 
 
941
  if mkdir:
942
  path.mkdir(parents=True, exist_ok=True) # make directory
 
943
  return path
944
 
945
 
 
933
  path = Path(path) # os-agnostic
934
  if path.exists() and not exist_ok:
935
  path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '')
936
+
937
+ # Method 1
938
+ for n in range(2, 9999):
939
+ p = f'{path}{sep}{n}{suffix}' # increment path
940
+ if not os.path.exists(p): #
941
+ break
942
+ path = Path(p)
943
+
944
+ # Method 2 (deprecated)
945
+ # dirs = glob.glob(f"{path}{sep}*") # similar paths
946
+ # matches = [re.search(rf"{path.stem}{sep}(\d+)", d) for d in dirs]
947
+ # i = [int(m.groups()[0]) for m in matches if m] # indices
948
+ # n = max(i) + 1 if i else 2 # increment number
949
+ # path = Path(f"{path}{sep}{n}{suffix}") # increment path
950
+
951
  if mkdir:
952
  path.mkdir(parents=True, exist_ok=True) # make directory
953
+
954
  return path
955
 
956