0

到目前为止,我已经尝试了很多我在网上找到的可能性,但我就是无法让它工作。我有这个代码:

def copytree(src, dst, symlinks=False, ignore=None):
    if not os.path.exists(dst):
        os.makedirs(dst)
    for item in os.listdir(src):
        s = str(os.path.join(src, item))
        d = str(os.path.join(dst, item))
        if os.path.isdir(s):
            copytree(s, d, symlinks, ignore)
        else:
            if not os.path.exists(d) or os.stat(s).st_mtime - os.stat(d).st_mtime > 1:
                shutil.copy2(s, d)

使用此代码,我可以将一个源文件夹中的所有文件复制到一个新的目标文件夹中。但是,如果源文件夹中有子文件夹,这总是会失败。代码已经在检查要复制的项目是文件夹还是单个文件,那么这段代码的问题在哪里?

4

1 回答 1

1

为此,您将需要使用import osand import shutil

参考这个作为例子:

import os
import shutil

for root, dirs, files in os.walk('.'):
   for file in files:
      path_file = os.path.join(root,file)
      shutil.copy2(path_file,'destination_directory')
于 2017-10-08T20:08:43.923 回答