Python实现文件夹中的每个文件存放到单独文件夹

通过Python实现文件单独存放

在一个文件夹中有许多的单独文件,如果我们需要将其单独放在文件自己的文件夹中,可以通过这种方式。
比如下图这样的结果,将“Pictures”文件夹中的每个文件夹里的图片,单独放到“Results”文件中。
在这里插入图片描述

实现

一共有两种迭代,一种是文件夹中的文件,另一种是文件夹中的文件夹中的文件(此为一类)。

文件夹中还有文件夹的情况

目录结构如图所示。
在这里插入图片描述
我将代码放到了文件的同级目录,具体可以根据自己的需要修改。

# 文件夹下的文件夹中的文件。
import os,shutil

#获取当前执行文件的目录。
currentPath=os.getcwd()
#目标文件所在的目录。
src_path=currentPath + '/Pictures/'

while True:
    fold_list=os.listdir(src_path)	# 得到目标文件夹的所有子目录。
    if len(fold_list)>0:
        for fold in fold_list:		# 迭代所有的子目录,fold就是子目录的名字。
            file_list = os.listdir(src_path + fold)	# 判断子目录中是否有文件。
            if len(file_list)>0:
                for file in file_list:	#迭代所有文件
                    # 拆解文件和后缀,保证新建的文件夹不包含后缀。
                    name, suffix = os.path.splitext(file)	
                    # 目标目录,可以根据自己的需要修改。
                    target_path = currentPath + '/Results/' + fold + '/' + name + '/'
                    # 判断是否有了当前文件。
                    newFolder = os.path.exists(target_path)
                    if (not newFolder):
                        os.makedirs(target_path)
                    # 复制文件
                    shutil.copy(src_path+ '/' + fold + '/' + file, target_path + file)

            print(fold, " Has Done!")

        break

文件夹中的文件

这一步只需要将代码中的子目录文件夹迭代去掉就好了。
效果如下图所示。
在这里插入图片描述

import os,shutil

currentPath=os.getcwd()
src_path=currentPath + '/NoChilds/'

while True:
    file_list = os.listdir(src_path)
    if len(file_list) > 0:
        for file in file_list:
            # New Floder.
            name, suffix = os.path.splitext(file)
            target_path = currentPath + '/Results/' + 'NoChilds/'+ name + '/'
            newFolder = os.path.exists(target_path)
            if (not newFolder):
                os.makedirs(target_path)
            shutil.copy(src_path + '/' + file, target_path + file)

    print("This Fold Has Done!")
    break

希望对大家有所帮助,互相学习。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值