需求:
将source_path路径下的所有文件和文件夹拷贝到target_path路径下
#! /usr/bin/python3
# -*- coding: utf-8 -*-
import os
import shutil
source_path = '/data/service/test/test1'
target_path = '/data/service/test/test2'
def copy_file(source_path,target_path):
file_list = os.listdir(source_path)
for file in file_list:
file_path = os.path.join(source_path,file)
if os.path.isfile(file_path):
shutil.copy(file_path,target_path)
elif os.path.isdir(file_path):
dir_name = os.path.basename(file_path)
target1_path = os.path.join(target_path,dir_name)
if not os.path.exists(target1_path):
os.makedirs(target1_path)
copy_file(file_path,target1_path)
else:
print('未知的文件类型')
if __name__ == '__main__':
copy_file(source_path,target_path)