近期在研究Python,随着学习的深入,发现越来越喜欢Python,其简洁的语法、丰富的库等,都给我这种希望快速对某个想法实施的人带来很多内心的喜悦。
话不多说,今天给大家分享两个函数,分别用来实现将某文件夹内所有文件或整个文件夹结构复制至指定文件夹
1、将某文件夹整体复制至指定文件夹
因为相对比较简单,只要大家对Python的OS熟悉,且知道递归函数的原理,基本可以看懂。
import os
def copy_dir(src_path, target_path):
if os.path.isdir(src_path) and os.path.isdir(target_path):
filelist_src = os.listdir(src_path)
for file in filelist_src:
path = os.path.join(os.path.abspath(src_path), file)
if os.path.isdir(path):
path1 = os.path.join(os.path.abspath(target_path), file)
if not os.path.exists(path1):
os.mkdir(path1)
copy_dir(path,path1)
else:
with open(path, 'rb') as read_stream:
contents = read_stream.read()
path1 = os.path.join(target_path, file)
with open(path1, 'wb') as write_stream:
write_stream.write(contents)
return True
else:
return False
以上函数,将src_path的文件夹整体复制到target_path内,包括子文件夹等,当然,前提是,这两个传入的文件路径均已存在,最后复制完毕后return True,如果传入的不是文件夹路径或文件夹路径不存在,则return False,以上函数已能满足我的需求,当然,大家如果有兴趣,可以对以上函数进行重写,或者使用装饰器进行装饰以添加新的功能。
2、将某文件夹下所有文件复制至指定文件夹内,但不复制该文件夹的结构
import os
import shutil
def copy_dirs(src_path,target_path):
‘‘‘copy all files of src_path to target_path’’’
file_count=0
source_path = os.path.abspath(src_path)
target_path = os.path.abspath(target_path)
if not os.path.exists(target_path):
os.makedirs(target_path)
if os.path.exists(source_path):
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)
file_count+=1
print(src_file)
return int(file_count)
该函数最后返回copy的文件个数,并且,不要求目标文件夹必须已存在,如果发现不存在,则会自动进行创建。
以上,欢迎交流,一起丰富Python,让Python变的更加活跃和流行!