python通过shutil.move移动文件夹内容(src,dst)在目标文件夹

时间:2018-05-16 02:41:54

标签: python shutil

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

  

shutil.move(src,dst)递归地将文件或目录(src)移动到   另一个地方(dst)。

     

如果目标是现有目录,则将src移入其中   那个目录。如果目的地已存在但不是   根据os.rename()语义,它可能会被覆盖。

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

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

shutil.move(staging_folder, final_folder)

搬家后:

https://snag.gy/GTfjNb.jpg

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

如果你能提供帮助,我们将不胜感激。

感谢。

3 个答案:

答案 0 :(得分:0)

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

<强>实施例

import shutil
import os

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

答案 1 :(得分:0)

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

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

if (\Request::isMethod('post')) {
        $adminUserDataExcelSelected = UserAdmin::getAdminUserListExcelSelected($request->selectedField, $request->selected)->get();
        $excelName = "Admin-Users".Carbon::now();
        $path = public_path('export/'.$excelName);

        ob_end_clean();
        ob_start();
        Excel::create($excelName, function($excel) use($adminUserDataExcelSelected) {
        $excel->sheet('Sheet 1', function($sheet) use($adminUserDataExcelSelected) {
        $sheet->fromArray($adminUserDataExcelSelected);
        });
        })->store('xlsx', public_path('exports'));
        ob_flush();
        //dd(url('/'));
        $creatingPath = url('/')."/exports/".$excelName.".xlsx";
        //return response()->download(public_path('a.xlsx'));
        return response()->json(['path' => $creatingPath]);
        //return response()->download($path);
    }

}

然后取消旧文件夹:

                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)

答案 2 :(得分:0)

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

相关问题