Rename files sequentially in python

2019-04-16 17:42发布

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.

1条回答
甜甜的少女心
2楼-- · 2019-04-16 18:04

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 .

查看更多
登录 后发表回答