Python 資料夾的拷貝操作

2022-05-06 04:54:09 字數 1366 閱讀 1799

在python中,想要實現資料夾的拷貝,需使用shutil包,其中檔案複製的內建函式為shutil.copy

這裡介紹兩種拷貝方式:

第一種為資料夾整體拷貝:

import

osimport

shutil

source_path = os.path.abspath(r'

e:\projects\source_dir')

target_path = os.path.abspath(r'

e:\projects\new folder\target_dir')

ifnot

os.path.exists(target_path):

#如果目標路徑不存在原資料夾的話就建立

os.makedirs(target_path)

ifos.path.exists(source_path):

#如果目標路徑存在原資料夾的話就先刪除

shutil.rmtree(target_path)

shutil.copytree(source_path, target_path)

print('

copy dir finished!

')

第二種為資料夾下的所有檔案(包括子目錄檔案)拷貝到目標資料夾下:

import

osimport

shutil

source_path = os.path.abspath(r'

e:\projects\source_dir')

target_path = os.path.abspath(r'

e:\projects\target_dir')

ifnot

os.path.exists(target_path):

os.makedirs(target_path)

ifos.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!

')

拷貝檔案 資料夾 建立資料夾 刪除資料夾操作

qt拷貝檔案 資料夾 建立資料夾 刪除資料夾操作 cpp view plain copy brief 拷貝檔案到目的資料夾 param srcfilename 原始檔全路徑,比如 f tx wwxx.txt f tx des desd param desfilepathname 要copy到的目的路...

拷貝資料夾

需要引用命名空間 using system.io 拷貝資料夾 包括子資料夾 到指定資料夾下,源資料夾和目標資料夾均需絕對路徑.格式 copyfolder 源資料夾,目標資料夾 public static void copyfolder string strfrompath,string strtop...

拷貝資料夾

需要引用命名空間 using system.io 拷貝資料夾 包括子資料夾 到指定資料夾下,源資料夾和目標資料夾均需絕對路徑.格式 copyfolder 源資料夾,目標資料夾 public static void copyfolder string strfrompath,string strtop...