Asori12 Asori12 - 3 years ago 118
Python Question

Rename files sequentially in python

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.

Answer Source

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 .

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download