Python遍历目录及子目录并将其中的文件复制到指定目录

 


import os, shutil  
from tqdm import tqdm
  
# 规范化绝对路径  
src_dir = os.path.abspath(r"I:\ADNI_DeepLearning\ADNI1 Annual 2 Yr 3T\MCI")  
dst_dir = os.path.abspath(r"I:\ADNI_DeepLearning_Copy\MCI")  
  
if not os.path.exists(dst_dir):  
    os.makedirs(dst_dir)  
# print("fistr_dir is:\t{}".format(fistr_dir))  
  
if os.path.exists(src_dir):  
    # root 所指的是当前正在遍历的这个文件夹的本身的地址  
    # dirs 是一个 list,内容是该文件夹中所有的目录的名字(不包括子目录)  
    # files 同样是 list, 内容是该文件夹中所有的文件(不包括子目录)  
    for root,dirs,files in os.walk(src_dir):  
        for file in tqdm(files):  
            src_file = os.path.join(root, file)  
            shutil.copy(src_file, dst_dir)  
            print(src_file)  
  
print('congratulations!')  

 

 

你可能感兴趣的:(python)