Rename files sequentially in python

限于喜欢 提交于 2019-12-10 00:03:16

问题


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:


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 .



来源:https://stackoverflow.com/questions/45286364/rename-files-sequentially-in-python

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