Rename files sequentially in python

十年热恋 提交于 2019-12-04 20:01:51

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 .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!