Incremental row number

I try to get the following output until a certain condition is met.

test_1.jpg
test_2.jpg
..
test_50.jpg

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


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

however ... this leads to the following result.

test_1.jpg
test_1_2.jpg
test_1_2_3.jpg
..... etc

Question: How can I change the number in the current place (without adding numbers to the end)?

Ps. I use this for a file rename tool.


UPDATE: Using various ideas below, I 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]
+3
source share
3 answers

Probably the easiest way is to save dstPath something like "test_% d.jpg" and just pass it a variable account:

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

[0] , ... , ,

+1

It seems that your condition os.path.exists(dstPath)matches the same renamed file several times. So, for example, it renames test.jpg to test_1.jpg; then renames test_1.jpg to test_1_2.jpg, etc.

0
source

Source: https://habr.com/ru/post/1744275/


All Articles