S1M0N_H
S1M0N_H

Reputation: 139

Python - Rename files and give them sequential number

I have quite a few files in this format:

file (2009).jpg
file (2010).jpg
file (2011).jpg

...etc

and I'd like to have them like this:

file (2009) (1).jpg
file (2009) (2).jpg
file (2009) (3).jpg

I can handle changing the date:

import os, re
for i in os.listdir('.'):
    os.rename(i, re.sub(r'\d{4}', '2009', i))

But I can't figure out how to have the sequential number added. I tried using a variable set to 1 and then incremented in the for loop, but I'm doing something wrong:

import os, re
n = 1
for i in os.listdir('.'):
    os.rename(i, re.sub(r'\d{4}', '2009', i))
    # use n to increment the filename, but how?

Thanks for any assisstance.

Upvotes: 1

Views: 6013

Answers (1)

AI Generated Response
AI Generated Response

Reputation: 8845

You can dynamically change the thing you're substituting in within your loop, like so

import os, re
n = 1
for i in os.listdir('.'):
    os.rename(i, re.sub(r'\(\d{4}\)', '(2009) ({n})'.format(n=n), i))
    n += 1

Upvotes: 4

Related Questions