python批量更改文件名——os.renames(old, new)用法

os.renames(old, new)

官方的解释:

Super-rename; create directories as necessary and delete any left empty. Works like rename, except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned until either the whole path is consumed or a nonempty directory is found.

Note: this function can fail with the new directory structure made if you lack permissions needed to unlink the leaf directory or file.

google翻译为:

超级重命名; 根据需要创建目录并删除任何留空的目录。 像重命名一样工作,除了首先尝试创建使新路径名良好所需的任何中间目录。 重命名后,与旧名称最右侧路径段对应的目录将被修剪,直到整个路径被消耗或找到非空目录。

注意:如果您缺乏取消链接叶目录或文件所需的权限,此功能可能会因新目录结构而失败。

源代码部分:

#传入两个地址,为绝对路径
def renames(old, new):
	#将新的路径按照最后一个'\'分割成两部分,即头和尾,即根目录和子文件名,例如’C:\\' 和 '1.jpg'
	head, tail = path.split(new)
		#判断头、尾是否存在,根目录不存在,则创建目录
	    if head and tail and not path.exists(head):
	        makedirs(head)
	    #开始改名
	    rename(old, new)
	    #同样分割处理
	    head, tail = path.split(old)
	    #使用os.rename()不能对根目录进行改变
	    if head and tail:
	        try:
	            removedirs(head)
	        except OSError:
	            pass

小结:os.rename()是一个更改文件名的基本命令,只能对根目录下的文件名进行更改,而os.renames()可以对根目录进行更改,在os.renames()内部嵌套os.name()。

这里也提供一个网站,可以查询python的一些内置方法的源代码和使用说明。

CodingDict

另外,也可以查询一些其他语言的源码。有些方法如果不是很清楚,可以直接查看源码。

栗子

将文件夹中的图片名称批量更改,保存在原目录下。

import os

def change_name(path):
    file_list = os.listdir(path)
    for i,each_file in enumerate(file_list):
        old_name = each_file
        #按照序号排列命名,只需要改这里和路径即可
        new_name = 'cat_' + str(i) + '_1.jpg'

        #这种情况下,两种方法没有区别,都能执行
        # os.rename(os.path.join(path,old_name),os.path.join(path,new_name))
        os.renames(os.path.join(path, old_name), os.path.join(path, new_name))

        print('成功将 {} 重命名为:{}'.format(old_name,new_name))

if __name__ == '__main__':
    change_name(path=r'F:/pycharm文件/hello pytorch/DATAS/orginal_image/training/')

效果如下:

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ERROR: Exception: Traceback (most recent call last): File "c:\program files\python\lib\shutil.py", line 788, in move os.rename(src, real_dst) PermissionError: [WinError 5] 拒绝访问。: 'c:\\program files\\python\\lib\\site-packages\\flask-1.1.2.dist-info\\' -> 'C:\\Users\\弦引\\AppData\\Local\\Temp\\pip-uninstall-0g0yzsps' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\弦引\AppData\Roaming\Python\Python38\site-packages\pip\_internal\cli\base_command.py", line 180, in exc_logging_wrapper status = run_func(*args) File "C:\Users\弦引\AppData\Roaming\Python\Python38\site-packages\pip\_internal\commands\uninstall.py", line 105, in run uninstall_pathset = req.uninstall( File "C:\Users\弦引\AppData\Roaming\Python\Python38\site-packages\pip\_internal\req\req_install.py", line 687, in uninstall uninstalled_pathset.remove(auto_confirm, verbose) File "C:\Users\弦引\AppData\Roaming\Python\Python38\site-packages\pip\_internal\req\req_uninstall.py", line 381, in remove moved.stash(path) File "C:\Users\弦引\AppData\Roaming\Python\Python38\site-packages\pip\_internal\req\req_uninstall.py", line 272, in stash renames(path, new_path) File "C:\Users\弦引\AppData\Roaming\Python\Python38\site-packages\pip\_internal\utils\misc.py", line 318, in renames shutil.move(old, new) File "c:\program files\python\lib\shutil.py", line 800, in move rmtree(src) File "c:\program files\python\lib\shutil.py", line 737, in rmtree return _rmtree_unsafe(path, onerror) File "c:\program files\python\lib\shutil.py", line 615, in _rmtree_unsafe onerror(os.unlink, fullname, sys.exc_info()) File "c:\program files\python\lib\shutil.py", line 613, in _rmtree_unsafe os.unlink(fullname) PermissionError: [WinError 5] 拒绝访问。: 'c:\\program files\\python\\lib\\site-packages\\flask-1.1.2.dist-info\\entry_points.txt'
07-22

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值