在python中顺序重命名文件 [英] Rename files sequentially in python

查看:304
本文介绍了在python中顺序重命名文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试重命名目录(test.jpeg,test1.jpeg,test2.jpeg等)中的文件(People-000,People-001,People-002等)

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...)

,但是我还没有找到在任何地方在线进行此操作的好方法。
我是python的新手,但是如果我发现它会非常有用。

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.

推荐答案

不用介意新旧名称之间的对应关系:

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 .

这篇关于在python中顺序重命名文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆