python基础语法
复制指定位置目录并将其拷贝到指定位置
import os
#将path1文件拷贝到path2文件
def filecopy(path1,path2):
with open(path1,'rb') as f:
date = f.read()
with open(path2,'wb') as fp:
fp.write(date)
def dircopy(path1,path2):
if os.path.isfile(path2):
print('存放路径不为目录,请确认后操作')
elif os.path.isfile(path1):
print('拷贝路径不为目录,请确认后操作')
else:
#列出path1的下的所有文件
fileList = os.listdir(path1)
#获的最后的目录名字
dirname =os.path.split(path1)[1]
#将目录名字拼接到新路径名上
dirpath = os.path.join(path2, dirname)
#判断目录是否存在
if os.path.exists(dirpath):
print('目录已存在')
exit(0)
else:
os.mkdir(dirpath)
for file in fileList:
#拼接要被copy的文件或目录的新位置
newpath1 = os.path.join(path1, file)
#判断文件是否为目录
if os.path.isdir(file):
#newpath1:要复制的目录 dirpath:目录存放位置
dircopy(newpath1,dirpath)
else:
#拼接路径名
newpath2 = os.path.join(dirpath, file)
#复制文件
filecopy(newpath1,newpath2)
#要复制的目录
path1 = r'E:\Qianfeng train\Qianfeng train code\project basics upper\homework\day13'
#目录存放的指定位置
path2 = r'E:\Qianfeng train\Qianfeng train code\project basics upper\homework\day13'
dircopy(path1,path2)