如何使用Python将目录及其内容复制到现有位置?

2024-07-08 16:02:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将目录及其所有内容复制到已存在的路径。问题是,在操作系统模块和shuil模块之间,似乎没有办法做到这一点。shutil.copytree()函数预期目标路径事先不存在。

我正在寻找的确切结果是将整个文件夹结构复制到另一个文件夹结构的顶部,并在找到的任何副本上自动覆盖。在我开始编写自己的函数来实现这一点之前,我想我会问是否有人知道现有的配方或代码片段可以实现这一点。


Tags: 模块函数路径目录文件夹内容目标副本
3条回答

对于像这样的高级文件操作,使用shutil模块和copytree函数。我认为这比“滥用”distutils更干净。

更新::忘记答案,我忽略了OP确实尝试过shuil。

为什么不自己使用os.walk实现呢?

^{}做你想做的事。

Copy an entire directory tree src to a new location dst. Both src and dst must be directory names. If src is not a directory, raise DistutilsFileError. If dst does not exist, it is created with mkpath(). The end result of the copy is that every file in src is copied to dst, and directories under src are recursively copied to dst. Return the list of files that were copied or might have been copied, using their output name. The return value is unaffected by update or dry_run: it is simply the list of all files under src, with the names changed to be under dst.

(更多文档请访问上述url)

相关问题 更多 >

    热门问题