字符串中的增量数

时间:2010-05-06 05:26:47

标签: python

我试图获得以下输出,直到满足某个条件。

test_1.jpg
test_2.jpg
..
test_50.jpg

我拥有的解决方案(如果您可以远程调用它)


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

问题:如何更改当前位置的数字(不添加数字到最后)?

聚苯乙烯。我正在使用它作为文件重命名工具。


更新:使用下面的各种想法,我发现了一个有效的循环


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]

5 个答案:

答案 0 :(得分:1)

将dstPath保留为“test_%d.jpg”可能最简单,只需将其传递给不同的数量:

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

答案 1 :(得分:1)

每次绕圈时打印出零件[0]的值......我想你可能会感到惊讶,

答案 2 :(得分:0)

好像您的条件os.path.exists(dstPath)多次匹配相同的重命名文件。例如,它将test.jpg重命名为test_1.jpg;然后将test_1.jpg重命名为test_1_2.jpg等。

答案 3 :(得分:0)

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

enter image description here

答案 4 :(得分:0)

针对Python v3.6 +的更新-使用source

for n in range(1,51):
    print(f'test_{n}')
相关问题