likes
comments
collection
share

python修改文件名的两种方法

作者站长头像
站长
· 阅读数 5

1 使用os模块中的os.rename(src, dst)修改文件名

1、os.rename(src, dst)

os.rename(src, dst)可以对文件或目录进行重新命名,把src重新命名为dst。但是有些需要注意的是:

  • 如把dir1/*.jpg 目录下所有的jpg图片进行重新命名,重新命名的图片依然保存到dir1目录下,重新命名后,此时该目录下只有重新命名后的图片,原图片名图片不存在了!
  • 如把dir1/*.jpg 目录下所有的jpg图片进行重新命名,重新命名的图片保存到dir2目录下,重新命名后,此时dir1目录下的dir/*.jpg 文件已经全部被改名并移动到dir2目录下!
import os

def rename_path():
    root = r'D:\dataset\konglie'
    paths = glob.glob(os.path.join(root, '*.bmp'))
    print(paths)
    for i, path in enumerate(paths):
        name = os.path.basename(path)
        os.rename(os.path.join(root, name), os.path.join(r'D:\dataset\konglie', '%05d.bmp' % i))
        
if __name__ == '__main__':
    rename_path

注意:

因为对原文件进行改名后,就不能改回去了,因此改名的时候要明确自己要修改成什么文件的名字。因为有些文件名起的是有含义的,因此防止后续想改回去或进行对比,因此要慎重!

shutil.move(src, dst)的效果和os.rename(src, dst) 一模一样,没有任何区别,二者可以等价使用,当然可能还有其他的接口也能够实现文件重命名的效果,大家可以自行探索!

如下是:shutil的一些其他接口

>>> import shutil
>>> shutil.
shutil.COPY_BUFSIZE               shutil.copymode(                  shutil.move(
shutil.Error(                     shutil.copystat(                  shutil.nt
shutil.ExecError(                 shutil.copytree(                  shutil.os
shutil.ReadError(                 shutil.disk_usage(                shutil.posix
shutil.RegistryError(             shutil.errno                      shutil.register_archive_format(
shutil.SameFileError(             shutil.fnmatch                    shutil.register_unpack_format(
shutil.SpecialFileError(          shutil.get_archive_formats(       shutil.rmtree(
shutil.chown(                     shutil.get_terminal_size(         shutil.stat
shutil.collections                shutil.get_unpack_formats(        shutil.sys
shutil.copy(                      shutil.getgrnam                   shutil.unpack_archive(
shutil.copy2(                     shutil.getpwnam                   shutil.unregister_archive_format(
shutil.copyfile(                  shutil.ignore_patterns(           shutil.unregister_unpack_format(
shutil.copyfileobj(               shutil.make_archive(              shutil.which(
>>> 

2 使用shutil模块中的shutil.copyfile(src, dst) 修改文件名

1、shutil.copyfile(src, dst)

shutil.copyfile(src, dst)拷贝文件,因此可以对拷贝后的src文件,进行重新命名后进行保存为dst

import shutil


def rename_path():
    root = r'D:\dataset\konglie'
    paths = glob.glob(os.path.join(root, '*.bmp'))
    print(paths)
    for i, path in enumerate(paths):
        name = os.path.basename(path)
        shutil.copyfile(os.path.join(root, name), os.path.join(r'D:\dataset\konglie_rename', '%05d.bmp' % i))
        
 if __name__ == '__main__':
     rename_path

我一般修改文件名都是使用shutil.copyfile(src, dst),其实就相当于是对原文件进行重命名后备份

常用的可能就这两种方法,欢迎大家补充!