首页 > 解决方案 > Python copy files script

问题描述

I built a script in Python to copy any files from a list of folders to a destination folder already made.

source = ['c:/test/source/', ]
destination = 'c:/test/destination/'

def copy(source, destination):

    import os, shutil

    try:
        for folder in source:
            files = os.listdir(folder)

            for file in files:
                current_file = os.path.join(folder, file)
                shutil.copy(os.path.join(folder, file), destination)

    except:
         pass

The problem with this script is that it didn't copy the sub folders. Any suggestion to fix it ?

Thanks

标签: python

解决方案


I think you need to use shutil.copytree

shutil.copytree(os.path.join(folder, file), destination)

but shutil.copytree won't overwrite if folder exist, if you want to overwrite all, use distutils.dir_util.copy_tree

from distutils import dir_util
dir_util.copy_tree(os.path.join(folder, file), destination)

推荐阅读