2

Hi i'm trying to rename my files in a directory from (test.jpeg, test1.jpeg, test2.jpeg etc...) (People-000, People-001, People-002 etc...)

but I haven't found a good way to do that anywhere online. I'm kinda new to python but if I figured this out it would be very useful.

5
  • 1
    stackoverflow.com/questions/2759067/rename-files-in-python i.e., use os.rename(src, dst) Commented Jul 24, 2017 at 17:13
  • What have you tried? Show code. For the vast majority of questions, if you have not included code showing what you have tried then your question is incomplete and needs more work. Commented Jul 24, 2017 at 17:26
  • I believe there is already an answer here. Check the below: <stackoverflow.com/questions/225735/…> Commented Jul 24, 2017 at 17:41
  • Here is what i tried 'import os n = 1 for i in os.listdir('/path/to/directory'): os.rename(i, 'People-(n)', i) n += 1 Commented Jul 24, 2017 at 17:56
  • 1
    @Asori12 sounds like your question is more about combining strings and numbers than renaming files. Commented Jul 24, 2017 at 18:02

1 Answer 1

9

If you don't mind correspondence between old and new names:

import os
_src = "/path/to/directory/"
_ext = ".jpeg"
for i,filename in enumerate(os.listdir(_src)):
    if filename.endswith(_ext):
        os.rename(filename, _src+'People-' + str(i).zfill(3)+_ext)

But if it is important that ending number of the old and new file name corresponds, you can use regular expressions:

import re
import os
_src = "/path/to/directory/"
_ext = ".jpeg"

endsWithNumber = re.compile(r'(\d+)'+(re.escape(_ext))+'$')
for filename in os.listdir(_src):
    m = endsWithNumber.search(filename)
    if m:
        os.rename(filename, _src+'People-' + str(m.group(1)).zfill(3)+_ext)
    else:
        os.rename(filename, _src+'People-' + str(0).zfill(3)+_ext)

Using regular expressions instead of string index has the advantage that it does not matter the file name length .

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this is the first version of sequential numbering that I can actually understand.

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.