[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')
第二步将合并后的所有文件按照不同文件类型分类整理。