-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
5
  • 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 :-) Commented Jun 11, 2018 at 11:54
  • i have all file names in one list . now how can i use os.rename function for each filename Commented Jun 11, 2018 at 12:00
  • Possible duplicate of Rename multiple files in Python Commented Jun 11, 2018 at 12:04
  • why python? wouldn't mv + sed do the same? Commented Jun 11, 2018 at 12:25
  • Did the below solution help? If so, feel free to accept, or ask for clarification. Commented Jun 13, 2018 at 8:48

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.