说明:调用方式为 python + 脚本文件名.py + 源路径 + 目标路径
1.仅复制一个文件夹
py -3 copy_dir.py test E:\badianboke1 E:\badianboke2
将test文件夹从 E:\badianboke1 复制到 E:\badianboke2
copy_single_dir.py 文件内容如下
import os
import sys
import stat
import shutil
class Copy_Single_Dir():
def __init__(self, dirName, fromPath, toPath):
self.dirName = dirName
self.fromPath = fromPath
self.toPath = toPath
def doCopy(self):
fromDir = os.path.join(self.fromPath, self.dirName)
toDir = os.path.join(self.toPath, self.dirName)
if not os.path.isdir(fromDir):
print('Source Dir is wrong!--badianboke')
return
if os.path.isfile(toDir):
print('Target is file but not dir, wrong target!--badianboke')
return
if os.path.exists(toDir):
shutil.rmtree(toDir, onerror = self.handleRemoveError)
shutil.copytree(fromDir, toDir)
print('copy single dir successfully')
def handleRemoveError(self, func, path, exe_info):
# 先授权,再删除
os.chmod(path, stat.S_IWRITE)
if os.path.isfile(path):
os.remove(path)
if os.path.isdir(path):
shutil.rmtree(path)
if __name__ == '__main__':
task = Copy_Single_Dir(sys.argv[1], sys.argv[2], sys.argv[3])
task.doCopy()
2.复制多个文件夹
py -3 copy_dir.py list.txt E:\badianboke1 E:\badianboke2
将list.txt内所列的所有文件夹从 E:\badianboke1 复制到 E:\badianboke2
dir1
dir2
dir3
copy_single_dir.py 文件内容如下
import os
import sys
import stat
import shutil
class Copy_Multi_Dir():
def __init__(self, dirName, fromPath, toPath):
self.dirName = dirName
self.fromPath = fromPath
self.toPath = toPath
def doCopy(self):
fromDir = os.path.join(self.fromPath, self.dirName)
toDir = os.path.join(self.toPath, self.dirName)
if not os.path.isdir(fromDir):
print('Source Dir is wrong!--badianboke')
return
if os.path.isfile(toDir):
print('Target is file but not dir, wrong target!--badianboke')
return
if os.path.exists(toDir):
shutil.rmtree(toDir, onerror = self.handleRemoveError)
shutil.copytree(fromDir, toDir)
print('copy single dir successfully')
def handleRemoveError(self, func, path, exe_info):
# 先授权,再删除
os.chmod(path, stat.S_IWRITE)
if os.path.isfile(path):
os.remove(path)
if os.path.isdir(path):
shutil.rmtree(path)
if __name__ == '__main__':
task = Copy_Single_Dir(sys.argv[1], sys.argv[2], sys.argv[3])
task.doCopy()
发表评论 取消回复