Question

I don't know much in Python, this is why I'm posting here. I currently have 480 files and their name is something like "Slide1", "Slide2", "Slide3" etc... The problem is that all the names have to be changed so that the first file will be called "Slide121", the second "Slide122", the third "Slide123" etc..

For the moment, I have this code :

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os

a = 121
b = 121

for filename in os.listdir('.'):
    if filename.startswith("Slide"):
        os.rename(filename, "Slide"+str(a)+"a.png")
        a += 1

for filename in os.listdir('.'):
    if filename.startswith("Slide"):
        os.rename(filename, "Slide"+str(b)+".png")
        b += 1

This should work, avoiding the error "this name already exists". The fact is that all the files have a new name, but the former "Slide1" file is now "Slide124", the former "Slide2" file is now "Slide85"... Nothing is at its initial place. Could you help me in some way ?

I apologize for my english by the way. THANKS.

Was it helpful?

Solution 2

You could use something like the script below.

Please make sure to have a backup of your slides in case the script doesn't work as intended.

import os
import re

REGEX = re.compile("Slide([0-9]+).png")

for filename in os.listdir('.'):
    match_ = re.match(REGEX, filename)
    if match_:
        slide_n = int(match_.group(1)) + 121
        os.rename(filename, "Slide{}.png".format(slide_n))

OTHER TIPS

Actually, both your and simon's approach will fail, because the system cannot rename Slide1 to Slide121 because there is already a Slide121. You should start with the highest numbered slide, like this:

import os

def main():
    for suffix in range(480,0,-1):
        os.rename("Slide%s.png" % suffix, "Slide%s.png" % (suffix + 120))

if __name__ == '__main__':
    main()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top