代码是python2写的,仅供参考和学习,有不足的地方希望能够提出来,一起学习,谢谢


# coding: utf-8
import os


def rename_plan_file(path):
    """
    重命名新生成的文件
    :param path: 文件路径加文件名,Reconstruction/outputplanfiles/TEMP_PLAN_202004140000_20200414074500.csv
    :return: 文件路径 + 新的文件名,Reconstruction/outputplanfiles/TEMP_PLAN_202004140000_20200414074500_1.csv
    """
    path_list = path.split("/")
    path = path_list[0] + "\\" + path_list[1]
    files = os.listdir(path)
    name = path_list[2]

    num = 1
    while True:
        name_list = name.split(".")

        # 判断文件名是否存在,存在则重命名
        if name in files:

            name = name_list[0] + "_{0}".format(num) + "." + name_list[1]

            # 判断重名之后的文件名有没有被使用,如果已被使用则再次重命名
            for i in files:
                if name == i:
                    new_num = int((name.split("_")[-1]).split(".")[0]) + num
                    name = name_list[0] + "_{0}".format(new_num) + "." + name_list[1]

            num += 1
        else:
            break

    new_path = os.path.join(path, name)

    return new_path


if __name__ == '__main__':
    path = "Reconstruction/outputplanfiles/TEMP_PLAN_202004140000_20200414074500.csv"
    rename_plan_file(path)

打赏

发表评论

邮箱地址不会被公开。 必填项已用*标注