【发布时间】:2013-03-17 19:40:52
【问题描述】:
我正在尝试使用 shutil.copytree:
shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=None)
此副本也是文件夹中的文件。我只需要复制没有任何文件的文件夹。怎么做?
【问题讨论】:
我正在尝试使用 shutil.copytree:
shutil.copytree(SOURCE_DIR, TARGET_DIR, ignore=None)
此副本也是文件夹中的文件。我只需要复制没有任何文件的文件夹。怎么做?
【问题讨论】:
您应该考虑使用os.walk。
Here is an example for os.walk。这样您就可以列出所有目录,然后使用os.mkdir 创建它们。
【讨论】:
您可以通过提供“忽略”功能来做到这一点
def ig_f(dir, files):
return [f for f in files if os.path.isfile(os.path.join(dir, f))]
shutil.copytree(SRC, DES, ignore=ig_f)
基本上,当您调用copytree 时,它会递归地转到每个子文件夹,并将该文件夹中的文件列表提供给忽略函数,以根据模式检查这些文件是否合适。被忽略的文件将在函数末尾作为列表返回,然后,copytree 将仅复制该列表中不包括的项目(在您的情况下,该列表包含当前文件夹中的所有文件)
【讨论】:
set(path for path in files if not os.path.isdir(...))。作为ignore 选项的一个不太有效的替代方案,copy_function=lambda *a, *kw: None 可用于在 Python 3.2+ 中禁用文件复制。
使用distutils.dir_util.create_tree 仅复制目录结构(不是文件)
注意:参数files 是一个文件名列表。如果你想要一些可以作为 shutils.copytree 的东西:
import os
import distutils.dir_util
def copy_tree(source, dest, **kwargs):
filenames = [os.path.join(path, file_) for path, _, files in os.walk(source) for file_ in files]
distutils.dir_util.create_tree(dest, filenames, **kwargs)
【讨论】:
这是基于os.walk() 的@Oz123's solution 的实现:
import os
def create_empty_dirtree(srcdir, dstdir, onerror=None):
srcdir = os.path.abspath(srcdir)
srcdir_prefix = len(srcdir) + len(os.path.sep)
os.makedirs(dstdir)
for root, dirs, files in os.walk(srcdir, onerror=onerror):
for dirname in dirs:
dirpath = os.path.join(dstdir, root[srcdir_prefix:], dirname)
try:
os.mkdir(dirpath)
except OSError as e:
if onerror is not None:
onerror(e)
【讨论】:
如果您想忽略 os.walk() 的模式功能,那么:
ignorePatterns=[".git"]
def create_empty_dirtree(src, dest, onerror=None):
src = os.path.abspath(src)
src_prefix = len(src) + len(os.path.sep)
for root, dirs, files in os.walk(src, onerror=onerror):
for pattern in ignorePatterns:
if pattern in root:
break
else:
#If the above break didn't work, this part will be executed
for dirname in dirs:
for pattern in ignorePatterns:
if pattern in dirname:
break
else:
#If the above break didn't work, this part will be executed
dirpath = os.path.join(dest, root[src_prefix:], dirname)
try:
os.makedirs(dirpath,exist_ok=True)
except OSError as e:
if onerror is not None:
onerror(e)
continue #If the above else didn't executed, this will be reached
continue #If the above else didn't executed, this will be reached
这将忽略.git 目录。
注意:这需要Python >=3.2,因为我使用了exist_ok 选项和makedirs,这在旧版本中不可用。
【讨论】:
上述答案有效,但它们肯定不会轻松,并且很容易花费您 30 分钟。如果您使用的是Windows,最快的方法是打开shell并使用xcopy,即:
c:\user> xcopy "source" "destination" /t /e
或者,如果你运行 Linux,你可以使用
rsync -a -f"+ */" -f"- *" source/ destination/
【讨论】: