[Python] - 遍历穿透多层套嵌文件夹复制文件

[Python] - 遍历穿透多层套嵌文件夹复制文件

因工作需要将套嵌文件夹下的所有文件合并整理到同一目录Coding如下。

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

"""
Created on Fri Oct 20 13:41:32 2023
@author: MZ_C
"""

import os
import shutil

# define/input 'src_path' & 'dst_path'
# 输入父级源文件夹路径和目标文件夹路径

src_path = input('Enter source file with full path: ')
dst_path = input('Enter target file with full path: ')

# Detect the destination folder and create a new one if it does not exist.
# 判断目标文件夹是否存在,若不存在则新建
if not os.path.exists(dst_path):
     os.mkdir(dst_path)
print(dst_path)

if not os.path.exists(src_path):
    print("Error: folder /"", src_path, "/" not exits!")

# Screen all the sub-folders and files under the source folder and indicate whether it's a folder or file.
# 遍历判断父级源文件夹路径下的文件夹&文件名
file_names = os.listdir(src_path)
for file_name in file_names:
    file_path = os.path.join(src_path, file_name)
    if os.path.isdir(file_path):
        print(file_name, " is dir")
    if os.path.isfile(file_path):
        print(file_name, " is file")

# Copy all the files from source folder to detination folder.
# 复制父级源文件夹路径下的全部文件到目标文件夹
for root,dirs,files in os.walk(src_path):
    for file in files:
        target = os.path.join(root, file)
        print(target)
        shutil.copy2(target, dst_path)
        print('copy  ' + dst_path)

print('\nFile copy is done!\n')

第二步将合并后的所有文件按照不同文件类型分类整理。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值