使用Python Shutil将文件复制到多个目录中

时间:2016-02-18 08:31:38

标签: python python-3.x shutil

我正在尝试使用shutil.copytree将目录复制到多个其他目录中。我无法让它发挥作用。我很确定我只需要实现ignore_errors=True,但我无法让它发挥作用。我应该如何实施' ignore_errors = True'进入

for CopyHere in DeleteThis:
    for CopyThis in FilestoCopy:
        shutil.copytree(CopyThis, CopyHere)
        print('Files have been copied')

我的代码如下:

import shutil
import time


DeleteThis = ['E:', 'F:']
FilestoCopy = ['C:\\Users\\2402neha\\Desktop\\Hehe']


for Directory_to_delete in DeleteThis: 
    shutil.rmtree(Directory_to_delete, ignore_errors=True)
    print('Directories have been wiped')
    time.sleep(2)


for CopyHere in DeleteThis:
    for CopyThis in FilestoCopy:
        shutil.copytree(CopyThis, CopyHere)
        print('Files have been copied')

以下是我收到的错误消息:

Traceback (most recent call last):
  File "C:\Users\2402neha\OneDrive\Python\Dis Cleaner\Copy paste test.py", line 17, in <module>
    shutil.copytree(CopyThis, CopyHere)
  File "C:\Users\2402neha\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 309, in copytree
    os.makedirs(dst)
  File "C:\Users\2402neha\AppData\Local\Programs\Python\Python35\lib\os.py", line 241, in makedirs
    mkdir(name, mode)
PermissionError: [WinError 5] Ingen tilgang: 'E:'

1 个答案:

答案 0 :(得分:0)

您的目的地为E:

目标目录不需要存在。

来自shutil.copytree的文档:

  

shutil.copytree(src, dst, symlinks=False, ignore=None)
  递归复制以src为根的整个目录树。目标目录(由dst命名)必须不存在;它将被创建以及缺少父目录。

您可能想要复制目录名并将其与目标一起加入:

directory = os.path.basename(CopyThis)
destination = os.path.join(CopyHere, directory)
shutil.copytree(CopyThis, destination)