python怎么復(fù)制文件夾

摘星
726
2021-05-26 08:09:32

python中復(fù)制文件夾的方法:1、在python腳本中導(dǎo)入os, shutil模塊;2、使用copy函數(shù)進(jìn)行文件夾復(fù)制操作即可。

python怎么復(fù)制文件夾

具體操作方法:

1、首先需要在python腳本中導(dǎo)入os, shutil模塊進(jìn)行文件操作。

import os, shutil

2、再使用copy函數(shù)進(jìn)行文件夾復(fù)制操作即可。

shutil.copy(source_file,target_ir) #source_file指源路徑, target_ir指目標(biāo)路徑

實(shí)例代碼:

1、文件夾整體拷貝。

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):

# 如果目標(biāo)路徑不存在原文件夾的話就創(chuàng)建

os.makedirs(target_path)

if os.path.exists(source_path):

# 如果目標(biāo)路徑存在原文件夾的話就先刪除

shutil.rmtree(target_path)

shutil.copytree(source_path, target_path)

print('copy dir finished!')

2、文件夾下的所有文件拷貝到目標(biāo)文件夾下。

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 所指的是當(dāng)前正在遍歷的這個(gè)文件夾的本身的地址

# dirs 是一個(gè) list,內(nèi)容是該文件夾中所有的目錄的名字(不包括子目錄)

# files 同樣是 list, 內(nèi)容是該文件夾中所有的文件(不包括子目錄)

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!')

相關(guān)函數(shù):

os.remove #刪除文件

os.rmdir #刪除文件夾

shutil.rmtree #刪除目錄及其所有內(nèi)容

0