文件批量改名

该代码实现了一个功能,遍历当前工作目录及其子目录,查找特定后缀的文件(如.xlsx和.csv),并将这些文件重命名为包含其原始目录名称的新文件,然后移动到名为'改名后'的新目录下。如果目标文件已存在于新目录中,则会打印错误信息。整个过程在遇到IOError时进行异常处理。
摘要由CSDN通过智能技术生成
# coding=utf-8
import os
from shutil import copyfile


def dealWith():
    DST_PREFIX = '改名后'
    root = os.getcwd()
    dstDir = os.path.sep.join((root, DST_PREFIX))
    suffixArray = ['.xlsx', '.csv']

    if not os.path.exists(dstDir):
        os.makedirs(dstDir)

    for parent, ds, fs in os.walk(root):
        if not parent == dstDir:
            for f in fs:
                dirName = os.path.basename(parent)
                for suffix in suffixArray:
                    if f.lower().endswith(suffix):
                        oldPath = os.path.sep.join((parent, f))
                        dstPath = os.path.sep.join((dstDir, dirName + "-" + f))
                        try:
                            if oldPath.startswith(DST_PREFIX):
                                print("error {}".format(oldPath))
                            copyfile(oldPath, dstPath)
                        except IOError as e:
                            print("copyoldPath = {},  erro = {}".format(oldPath, e))
                        finally:
                            pass


if __name__ == '__main__':
    dealWith()
    print("main finish.")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值