python通过shutil.move(src,dst)移动文件夹内容在目标文件夹中创建整个源文件夹

python move folder contents via shutil.move(src, dst) creates entire source folder in target folder

我感觉shutil.move(src,dst)可以完成这项工作,但是,根据python 2文档:

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

1
shutil.move(staging_folder, final_folder)

移动后:

https://snag.gy/GTfjNb.jpg

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

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

谢谢。


事实证明,该路径不正确,因为其中包含错误解释的\ t。

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

1
2
3
4
5
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)

然后清空旧文件夹:

1
2
3
4
5
6
7
8
9
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)

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

例如:

1
2
3
4
5
import shutil
import os

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