开发者

Increment number in string

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


fileCoun开发者_如何学JAVAt = 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.


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]


It's probably easiest to keep dstPath something like "test_%d.jpg", and just pass it a varying count:

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


Print out the value of parts[0] each time you go round the loop ... I think you may be surprised,


It seems as though your condition os.path.exists(dstPath) is matching the same renamed file multiple times. So for example, it renames test.jpg to test_1.jpg; then renames test_1.jpg to test_1_2.jpg, etc.


for j in range(1,10):
    print("test_{0}.jpg".format(j))

enter image description here


Update for Python v3.6+ - using formatted string literals:

for n in range(1,51):
    print(f'test_{n}')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜