在Python中,想要實現文件夾的拷貝,需使用shutil包,其中文件復制的內置函數為shutil.copy
這里介紹兩種拷貝方式:
第一種為文件夾整體拷貝:
import os import shutil source_path = os.path.abspath(r'E:\Projects\source_dir') target_path = os.path.abspath(r'E:\Projects\new folder\target_dir') if not os.path.exists(target_path): # 如果目標路徑不存在原文件夾的話就創建 os.makedirs(target_path) if os.path.exists(source_path): # 如果目標路徑存在原文件夾的話就先刪除 shutil.rmtree(target_path) shutil.copytree(source_path, target_path) print('copy dir finished!')
第二種為文件夾下的所有文件(包括子目錄文件)拷貝到目標文件夾下:
import os import shutil source_path = os.path.abspath(r'E:\Projects\source_dir') target_path = os.path.abspath(r'E:\Projects\target_dir') if not os.path.exists(target_path): os.makedirs(target_path) if os.path.exists(source_path): # root 所指的是當前正在遍歷的這個文件夾的本身的地址 # dirs 是一個 list,內容是該文件夾中所有的目錄的名字(不包括子目錄) # files 同樣是 list, 內容是該文件夾中所有的文件(不包括子目錄) for root, dirs, files in os.walk(source_path): for file in files: src_file = os.path.join(root, file) shutil.copy(src_file, target_path) print(src_file) print('copy files finished!')