Python批量重命名修改固定后缀名的文件

2022-07-26,,,,

Python批量重命名修改固定后缀名的文件

  • Python 基于OS实现文件批量重命名

Python 基于OS实现文件批量重命名

批量修改文件夹内固定后缀名的文件,以“.JPG” 格式为例,可自定义路径,本例在当前文件夹下新建了 “Newtrans” 文件夹作为新文件的保存

重命名后原文件夹里的文件会消失,不放心的记得备份

import os


def transform(Path):
    """
    转换函数
    :param Path:目标文件夹的路径
    :return:
    """

    # 找到当前路径里所有以 “.JPG” 为后缀名的文件
    file_list = [x for x in os.listdir(Path + "\\") if x.endswith(".JPG")]
    print("There are {} files".format(len(file_list)))

    i = 0
    for file in file_list:
        os.rename(os.path.join(Path, file),
                  os.path.join(Path+"\\Newtrans\\", 
                  "{}.JPG".format(i + 1)))
        i += 1
        print('All: ', len(file_list), '  Remaining: ', len(file_list) - i - 1)

    return


if __name__ == '__main__':
    print("=== Start Transform... === ")
    Path = "D:\\Your Path"
    transform(Path)
    print("=== Transform Finished !!! === ")
   

完结撒花,以后再写修改文件夹名称什么的,基本一个意思。

本文地址:https://blog.csdn.net/Other_stone/article/details/110875465

《Python批量重命名修改固定后缀名的文件.doc》

下载本文的Word格式文档,以方便收藏与打印。