Python 修改 子文件 与 当前文件夹 同名

【随时记录好用的代码  以防后续使用忘记  整体思路源于自己搜索+总结】

——————————————————————————————————————

如果遇到一个人一个文件夹内部还带有一个子文件的情况,还有好几个人,就很让人头疼。想着把子文件名换成当前所在文件夹的人名部分(不要编号),也许会方便检索一点。(开头的一些废话,不用看)

现在的情况:

 目标结果:

 所需代码如下:

import os

# Change the file name to be the same as the current folder name
def change_name(path):
    flag = 0
    for root, dirs, files, in os.walk(path):
        # Skip the first loop and print root, dirs, files to see why
        if flag == 0:
            flag = 1
            continue

        # Get the Chinese part of folder name
        folderName = root.split('/')[-1]
        folderName_C = folderName.split('_')[1]

        # Only one file in each folder, so get the first file (Modify as needed)
        fileName = files[0]

        # Filename without suffix
        fileNameNoSuffix = fileName.split('.')[0]

        # Suffix default as empty
        suffix = ''

        # Sequentially store file suffixes different from the folder name
        if(fileName != fileNameNoSuffix):
            suffix = '.' + fileName.split('.')[1]

        # Rename
        originName = path + folderName + '/' + fileName
        newName = path + folderName + '/' + folderName_C + suffix
        os.rename(originName, newName)


change_name(r'./AAAA Hospital/EyeKnow0/')

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值