簡體   English   中英

如何在不復制python中的文件夾結構的同時從文件夾(包括子文件夾)復制所有文件

[英]How to copy all files from a folder (including sub-folder) while not copying the folder structure in python

有人可以幫助我如何將文件夾中的所有文件復制到python中的另一個目標文件夾。 問題是我不想復制子目錄結構。 但我想要其中的文件。

例如,假設在根文件夾中,有3個文件夾,每個文件夾包含10個文件。 每個文件夾中還有2個文件夾,每個文件夾包含5個文件。 (因此每個第一級文件夾總共有20個文件和2個子目錄)。 總計60個文件。

我希望將所有這60個文件復制到一個目標目錄,丟棄子文件夾結構。

這是我試過的代碼:

# path : source folder path
# compiled_path: destination folder path
w = os.walk(path)
for root, dirs, files in w:
    for dir_name in dirs:
        file_list_curent_dir = os.walk(path+"\\"+dir_name).next()[2]
        for item in file_list_curent_dir:
            shutil.copy(path+"\\"+dir_name+"\\"+item, compiled_path+"\\"+item )

它復制文件的最高級別,而不是子目錄中的文件夾。

非常感謝您的寶貴時間。

import os
import shutil

for root, dirs, files in os.walk('.'):  # replace the . with your starting directory
   for file in files:
      path_file = os.path.join(root,file)
      shutil.copy2(path_file,'destination_directory') # change you destination dir

你可以使用這個原始函數(但是當你想以遞歸方式遍歷目錄時最好的方法是os.walk)

from shutil import copyfile
import shutil
def your_function(dir):
    for folder in os.listdir(dir):
        folder_full_path = os.path.join(dir,folder)
        move_down_and_delete(folder_full_path,folder_full_path)

def move_down_and_delete(input,copy_to_dir):
    if os.path.isfile(input):
        dest = os.path.join(copy_to_dir,os.path.basename(input))
        print dest,input
        copyfile(input,dest)
        return
    for child in os.listdir(input):
         current_obj_path = os.path.join(input, child)
         move_down_and_delete(current_obj_path,copy_to_dir)
         if not os.path.isfile(current_obj_path):shutil.rmtree(current_obj_path)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM