1、文件夹中不含文件夹
import os
src_path = r'c:\p1'
target_path = r'c:\p2'
def copy(src,target):
if os.path.isdir(src) and os.path.isdir(target):
filelist = os.listdir(src)
for file in filelist:
path = os.path.join(src,file)
with open(path,'rb') as rstream:
container = rstream.read()
path1 = os.path.join(target,file)
with open(path1,'wb') as wstream:
wstream.write(container)
else:
print("复制完毕")
copy(src_path,target_path)
2、文件夹中含文件夹(通用)
import os
src_path = r'c:\p1'
target_path = r'c:\p2'
def copy(src_path,target_path):
filelist = os.listdir(src_path)
for file in filelist:
path = os.path.join(src_path,file)
if os.path.isdir(path):
copy(path,target_path)
else:
with open(path,'rb') as rstream:
container = rstream.read()
path1 = os.path.join(target_path,file)
with open(path1,'wb') as wstream:
wstream.write(container)
else:
print('复制完成')
3、补充
for else语法在python是存在的,如果for循环正常结束,else中语句执行。如果break跳出for循环则不执行。