在python中复制目录

问题描述 投票:0回答:1

当我想将文件夹从特定文件夹复制到另一个文件夹时,出现错误。您能向我解释一下为什么会发生这种情况吗?

    import shutil
    os.chdir('/content/gdrive/MyDrive/Data1')
    for subfolder in os.listdir(os.getcwd()):
      if subfolder!='MyData':
        for file in os.listdir(subfolder):
          if file.endswith('.mp4'):
            name_only = file.split('.')[0]
            name=name_only+'-opencv'
            path='/content/gdrive/MyDrive/Data1/MyData/'+ subfolder
            path1='/content/gdrive/MyDrive/Data1/'+subfolder+'/'+name
    # to copy directories from a specific folder to another one.
            shutil.copytree(path1,path)

---------------------------------------------------------------------------
    FileExistsError                           Traceback (most recent call last)
    <ipython-input-75-642989479aae> in <cell line: 3>()
          9         path='/content/gdrive/MyDrive/Data1/MyData/'+ subfolder
         10         path1='/content/gdrive/MyDrive/Data1/'+subfolder+'/'+name
    ---> 11         shutil.copytree(path1,path)

    2 frames
    /usr/lib/python3.10/os.py in makedirs(name, mode, exist_ok)
        223             return
        224     try:
    --> 225         mkdir(name, mode)
        226     except OSError:
        227         # Cannot rely on checking for EEXIST, since the operating system

    FileExistsError: [Errno 17] File exists: '/content/gdrive/MyDrive/Data1/MyData/Red'
python directory copy copy-paste shutil
1个回答
0
投票

注意错误: “FileExistsError”,您正在尝试写入存在相同文件夹的文件夹。 您可以使用与 @Barmar 注释相同的 dirs_exist_ok =True 作为 copytree 函数中的参数,例如:

shutil.copytree(path1,path, dirs_exist_ok=True)

或者,如果您不想覆盖,您可以轻松检查要写入的文件夹是否存在。

© www.soinside.com 2019 - 2024. All rights reserved.