Skip to content

Commit 1a3ecb8

Browse files
authored
increment_path() robustness improvements (#7628)
Improved robustness to filename edge cases like `data/images/zidane.23.jpg` that currently fail. May resolve #7432
1 parent 177da7f commit 1a3ecb8

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

utils/general.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -933,13 +933,24 @@ def increment_path(path, exist_ok=False, sep='', mkdir=False):
933933
path = Path(path) # os-agnostic
934934
if path.exists() and not exist_ok:
935935
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
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+
941951
if mkdir:
942952
path.mkdir(parents=True, exist_ok=True) # make directory
953+
943954
return path
944955

945956

0 commit comments

Comments
 (0)