在 Python 中递归复制文件或目录

编程入门 行业动态 更新时间:2024-10-28 03:27:11
本文介绍了在 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 中递归复制文件或目录

本文发布于:2023-10-09 09:24:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1475353.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   文件   目录   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!