在 Python 中递归复制文件或目录 [英] Copy file or directories recursively in Python

查看:75
本文介绍了在 Python 中递归复制文件或目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 似乎有复制文件的功能(例如 shutil.copy)和复制目录的功能(例如 shutil.copytree),但我没有找到任何功能处理两者.当然,检查您是要复制文件还是目录很简单,但这似乎是一个奇怪的遗漏.

Python seems to have functions for copying files (e.g. shutil.copy) and functions for copying directories (e.g. shutil.copytree) but I haven't found any function that handles both. Sure, it's trivial to check whether you want to copy a file or a directory, but it seems like a strange omission.

真的没有像 unix cp -r 命令那样工作的标准函数,即支持目录和文件并递归复制吗?在 Python 中解决这个问题的最优雅的方法是什么?

Is there really no standard function that works like the unix cp -r command, i.e. supports both directories and files and copies recursively? What would be the most elegant way to work around this problem in Python?

推荐答案

我建议你先打电话给 shutil.copytree,如果抛出异常,则使用 shutil.copy.

I suggest you first call shutil.copytree, and if an exception is thrown, then retry with shutil.copy.

import shutil, errno

def copyanything(src, dst):
    try:
        shutil.copytree(src, dst)
    except OSError as exc: # python >2.5
        if exc.errno == errno.ENOTDIR:
            shutil.copy(src, dst)
        else: raise

这篇关于在 Python 中递归复制文件或目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆