Skip to content

Commit

Permalink
Merge pull request psychopy#6917 from TEParsons/dev-ff-file-collision
Browse files Browse the repository at this point in the history
FF: Fix filename collision iterations
  • Loading branch information
TEParsons authored Oct 16, 2024
2 parents b6ddfca + 5001a36 commit 566f2aa
Showing 1 changed file with 20 additions and 21 deletions.
41 changes: 20 additions & 21 deletions psychopy/tools/fileerrortools.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"""
import os
import glob
from pathlib import Path

from psychopy import logging

Expand All @@ -32,27 +33,25 @@ def handleFileCollision(fileName, fileCollisionMethod):
"fileCollisionMethod to overwrite.")
raise IOError(msg % fileName)
elif fileCollisionMethod == 'rename':
rootName, extension = os.path.splitext(fileName)

# make extension iterable
if extension:
allowedExt = [extension]
else:
allowedExt = [
os.path.splitext(match)[1] for match in
glob.glob("%s*" % rootName)
]
# get extension (from options) with most files
nFiles = 0
for ext in allowedExt:
matchingFiles = glob.glob("%s*%s" % (rootName, ext))
nFiles = max(nFiles, len(matchingFiles))

# Build the renamed string.
if not nFiles:
fileName = "%s%s" % (rootName, extension)
else:
fileName = "%s_%d%s" % (rootName, nFiles, extension)
# convert to a Path object
fileObj = Path(fileName)
# use a glob star if we don't have an ext
if not fileObj.suffix:
fileObj = fileObj.parent / (fileObj.stem + ".*")
# get original file name
rootName = fileObj.stem
# get total number of sibling files to use as maximum for iteration
nSiblings = len(list(fileObj.parent.glob("*")))
# iteratively add numbers to the end until filename isn't taken
i = 0
while list(fileObj.parent.glob(fileObj.name)) and i < nSiblings:
i += 1
fileObj = fileObj.parent / (f"{rootName}_{i}" + fileObj.suffix)
# remove glob star from suffix if needed
if fileObj.suffix == ".*":
fileObj = fileObj.parent / fileObj.stem
# convert back to a string
fileName = str(fileObj)

# Check to make sure the new fileName hasn't been taken too.
if os.path.exists(fileName):
Expand Down

0 comments on commit 566f2aa

Please sign in to comment.