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 中递归复制文件或目录
发布评论