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.

Asori12
  • 133
  • 1
  • 14
  • 1
    https://stackoverflow.com/questions/2759067/rename-files-in-python i.e., use os.rename(src, dst) – anugrah Jul 24 '17 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. – Jacobr365 Jul 24 '17 at 17:26
  • I believe there is already an answer here. Check the below: – Ankit Jul 24 '17 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 – Asori12 Jul 24 '17 at 17:56
  • 1
    @Asori12 sounds like your question is more about combining strings and numbers than renaming files. – Alex Hall Jul 24 '17 at 18:02

1 Answers1

8

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 .

alvarez
  • 456
  • 3
  • 9