Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python复制文件脚本_Python - Fatal编程技术网

Python复制文件脚本

Python复制文件脚本,python,Python,我用Python构建了一个脚本,将文件夹列表中的任何文件复制到已创建的目标文件夹中 source = ['c:/test/source/', ] destination = 'c:/test/destination/' def copy(source, destination): import os, shutil try: for folder in source: files = os.listdir(folder)

我用Python构建了一个脚本,将文件夹列表中的任何文件复制到已创建的目标文件夹中

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
此脚本的问题在于它没有复制子文件夹。有什么建议可以解决吗

谢谢

我想你需要使用

但是如果文件夹存在,
shutil.copytree
将不会覆盖, 如果要覆盖所有,请使用


是的,它几乎可以工作了,但还有一个问题。实际上,脚本告诉我已经有一个名为“destination”的文件夹。我想要的是强制复制文件夹、文件和子文件夹(如果它们已经存在)。是,它会覆盖所有文件。但还有最后一个问题!:)未创建子文件夹。。。所以我有这样的错误:distutils.errors.DistutilsFileError:无法创建'c:/test/destination\Nouveau dossier\Nouveau document texte(2.txt)':没有这样的文件或目录我必须自己创建子文件夹才能让它工作。有解决方案吗?你说的子文件夹是什么意思?例如,如果您有文件夹
name1
,您需要将文件夹
name1
复制到文件夹
name2
,但您没有
name2
文件夹,它将创建它,但如果您没有
name1
它将引发
DistutilsFileError
您需要在源文件夹中有
name1
文件夹,我有文件和其他文件夹,其中可能包含其他文件和其他文件夹。所以我想复制目标文件夹中的所有内容。但是,如果我有“c:/test/source/subfolder/file.txt”,并且我的目标文件夹存在但为空,则会出现错误。
shutil.copytree(os.path.join(folder, file), destination)
from distutils import dir_util
dir_util.copy_tree(os.path.join(folder, file), destination)