-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
  • 74,910
  • 12
  • 133
  • 166
Issam_Qa
  • 1
  • 1
  • 4
    Sounds like a fun project. Go ahead and try it out. Let us know if you have a specific answerable question, and we'll help you out then :-) – Kevin Jun 11 '18 at 11:54
  • i have all file names in one list . now how can i use os.rename function for each filename – Issam_Qa Jun 11 '18 at 12:00
  • Possible duplicate of [Rename multiple files in Python](https://stackoverflow.com/questions/17748228/rename-multiple-files-in-python) – Ankur Sinha Jun 11 '18 at 12:04
  • why python? wouldn't `mv` + `sed` do the same? –  Jun 11 '18 at 12:25
  • Did the below solution help? If so, feel free to accept, or ask for clarification. – jpp Jun 13 '18 at 08:48

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
  • 159,742
  • 34
  • 281
  • 339