在满足特定条件之前,我将尝试获取以下输出。

test_1.jpg
test_2.jpg
..
test_50.jpg

The solution (if you could remotely call it that) that I have is


fileCount = 0
while (os.path.exists(dstPath)):
   fileCount += 1
   parts = os.path.splitext(dstPath)
   dstPath = "%s_%d%s" % (parts[0], fileCount, parts[1])

但是…这会产生以下输出。
test_1.jpg
test_1_2.jpg
test_1_2_3.jpg
.....etc

The Question: How do I get change the number in its current place (without appending numbers to the end)?

Ps. I'm using this for a file renaming tool.


UPDATE: Using various ideas below, i've discovered a loop that works


dstPathfmt = "%s_%d%s"
parts = os.path.splitext(dstPath)
fileCount = 0
while (os.path.exists(dstPath)):
   fileCount += 1
   dstPath = parts[0]+"_%d"%fileCount+parts[1]

最佳答案

保持dstPath类似于“test_%d.jpg”可能是最简单的,只需通过不同的计数即可:

dstPath = "test_%d.jpg"
i = 1
while os.path.exists(dstPath % i):
    i += 1
dstPath = dstPath % i # Final name

10-01 16:05