使用python将目录内容复制到目录中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15034151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:09:36  来源:igfitidea点击:

Copy directory contents into a directory with python

pythonshutilcopytree

提问by prosseek

I have a directory /a/b/c that has files and subdirectories. I need to copy the /a/b/c/* in the /x/y/z directory. What python methods can I use?

我有一个包含文件和子目录的目录 /a/b/c。我需要复制 /x/y/z 目录中的 /a/b/c/* 。我可以使用哪些 Python 方法?

I tried shutil.copytree("a/b/c", "/x/y/z"), but python tries to create /x/y/z and raises an error "Directory exists".

我试过了shutil.copytree("a/b/c", "/x/y/z"),但 python 试图创建 /x/y/z 并引发一个error "Directory exists".

采纳答案by prosseek

I found this code working:

我发现此代码有效:

from distutils.dir_util import copy_tree

# copy subdirectory example
fromDirectory = "/a/b/c"
toDirectory = "/x/y/z"

copy_tree(fromDirectory, toDirectory)

Reference:

参考:

回答by ikudyk

You can also use glob2 to recursively collect all paths (using ** subfolders wildcard) and then use shutil.copyfile, saving the paths

您还可以使用 glob2 递归收集所有路径(使用 ** 子文件夹通配符),然后使用shutil.copyfile,保存路径

glob2 link: https://code.activestate.com/pypm/glob2/

glob2 链接:https://code.activestate.com/pypm/glob2/

回答by kutenzo

The python libs are obsolete with this function. I've done one that works correctly:

这个函数的python库已经过时了。我做了一个工作正常的:

import os
import shutil

def copydirectorykut(src, dst):
    os.chdir(dst)
    list=os.listdir(src)
    nom= src+'.txt'
    fitx= open(nom, 'w')

    for item in list:
        fitx.write("%s\n" % item)

    fitx.close()

    f = open(nom,'r')
    for line in f.readlines():
        if "." in line:
            shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
        else:
            if not os.path.exists(dst+'/'+line[:-1]):
                os.makedirs(dst+'/'+line[:-1])
                copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
            copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
    f.close()
    os.remove(nom)
    os.chdir('..')

回答by Brad

from subprocess import call

def cp_dir(source, target):
    call(['cp', '-a', source, target]) # Linux

cp_dir('/a/b/c/', '/x/y/z/')

It works for me. Basically, it executes shell command cp.

这个对我有用。基本上,它执行 shell 命令cp