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

python move folder contents without moving the source folder

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

这不是我想要的,我希望将暂存文件夹中的所有内容移至文件夹 "final" 下,我不需要 "staging" 文件夹本身。

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

谢谢。

您可以使用 os.listdir 然后将每个文件移动到所需的目的地。

例如:

import shutil
import os

for i in os.listdir(staging_folder):
    shutil.move(os.path.join(staging_folder, i), final_folder)

事实证明路径不正确,因为它包含被误解的 \t。

我最终使用了 shutil.move + shutil.copy22

for i in os.listdir(staging_folder):
    if not os.path.exists(final_folder):
        shutil.move(os.path.join(staging_folder, i), final_folder)
    else:
        shutil.copy2(os.path.join(staging_folder, i), final_folder)

然后清空旧文件夹:

def emptify_staging(self, folder):
    for the_file in os.listdir(folder):
        file_path = os.path.join(folder, the_file)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
                # elif os.path.isdir(file_path): shutil.rmtree(file_path)
        except Exception as e:
            print(e)

您可以使用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']