-1

I have multiple files in a directory :

00- filename1
01- filename2
02- filename3
03- filename4

etc. I am trying to replace 00 in the file name with 01, and 01 ==> 02 Using Python. which would result in the following:

01- filename1
02- filename2
03- filename3
04- filename4
Kevin
  • 72,202
  • 12
  • 116
  • 152
Issam_Qa
  • 1
  • 1

1 Answers1

0

Start by considering how you'd approach this with a list. Note f-strings, or formatted string literals, are available in Python 3.6+.

A = ['00- filename1', '01- filename2', '02- filename3', '03- filename4']

def renamer(x):
    num, name = x.split('-')
    newnum = str(int(num)+1).zfill(2)
    return f'{newnum}-{name}'

res = [renamer(i) for i in A]

print(res)

['01- filename1', '02- filename2', '03- filename3', '04- filename4']

Then incorporate this into file cycling logic. For example:

import os

for fn in os.listdir('.'):
    os.rename(fn, renamer(fn))
jpp
  • 147,904
  • 31
  • 244
  • 302