python移动文件夹内容而不移动源文件夹

标签 python shutil

shutil.move(src, dst) 是我认为可以完成的工作,但是,根据 python 2 document :

shutil.move(src, dst) Recursively move a file or directory (src) to another location (dst).

If the destination is an existing directory, then src is moved inside that directory. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics.

这与我的情况有点不同,如下所示:

搬家前: https://snag.gy/JfbE6D.jpg

shutil.move(staging_folder, final_folder)

移动后:

https://snag.gy/GTfjNb.jpg

这不是我想要的,我希望将 staging 文件夹中的所有内容移动到文件夹“final”下,我不需要“staging”文件夹本身。

如能提供帮助,将不胜感激。

谢谢。

最佳答案

您可以使用 shutil.copytree()staging_folder 中的所有内容移动到 final_folder 而无需移动 staging_folder 。调用函数时传递参数 copy_function=shutil.move

对于 Python 3.8:

shutil.copytree('staging_folder', 'final_folder', copy_function=shutil.move, dirs_exist_ok=True)

对于 Python 3.7 及以下版本:

请注意参数 dirs_exist_ok 不受支持。目标 final_folder 不得已存在,因为它将在移动过程中创建。

shutil.copytree('staging_folder', 'final_folder', copy_function=shutil.move)

示例代码(Python 3.8):

>>> os.listdir('staging_folder')
['file1', 'file2', 'file3']

>>> os.listdir('final_folder')
[]

>>> shutil.copytree('staging_folder', 'final_folder', copy_function=shutil.move, dirs_exist_ok=True)
'final_folder'

>>> os.listdir('staging_folder')
[]

>>> os.listdir('final_folder')
['file1', 'file2', 'file3']

关于python移动文件夹内容而不移动源文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50361720/

相关文章:

python - 编写 MongoDB 查询来根据引用的属性进行过滤?

python - 用于捕获所有出现的由一系列字符分隔的文本的正则表达式

python - python中删除多个目录

python - 将文件夹中的文件移动到顶级目录

python - 将子目录中的特定文件移动到目录中 - python

python - Errno 22 无效参数 Python

python - shutil.rmtree() 说明

python - 使用非连接图或工具 Python 的车辆路径问题

python - 如何将不存在的类成员函数动态转换为现有的

python:单词和词形词典