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

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

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

165536 次浏览

我发现这个代码可以工作,它是标准库的一部分:

from distutils.dir_util import copy_tree


# copy subdirectory example
from_directory = "/a/b/c"
to_directory = "/x/y/z"


copy_tree(from_directory, to_directory)

参考文献:

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

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

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

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('..')
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.