Increment number in string

Posted by iform on Stack Overflow See other posts from Stack Overflow or by iform
Published on 2010-05-06T05:26:46Z Indexed on 2010/05/06 5:28 UTC
Read the original article Hit count: 161

Filed under:

Hi, I am stumped...

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

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])

however...this produces the following output.

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.

© Stack Overflow or respective owner

Related posts about python