在做cocos2dx-js的时候每次打测试包都要拷贝js到打包环境中,但是又有很多文件不想拷贝进去,所以就用python写了一个脚本来进行拷贝粘贴,顺便学习了一下python。代码非常简单,第一个功能是直接拷贝整个文件夹,第二个功能是遍历判定后缀名拷贝,但是还是会创建文件夹路径(暂时没有优化掉,我的一个思路是先判定当前路径树下是否有需要拷贝的文件,但是感觉复杂度瞬间就高了,暂时没有好的解决方案,先堆积),直接贴代码:
#coding=utf-8
import shutil
import os
class CopyFileUtil:
@classmethod
def CopyFileFromTo(cls, strFrom, strTo):
if os.path.isfile(strFrom):
shutil.copyfile(strFrom, strTo)
else:
for fileName in os.listdir(strFrom):
sourceFileName = os.path.join(strFrom, fileName)
targetFileName = os.path.join(strTo, fileName)
#如果源文件一个文件
#1.判断目标路径是否存在 不存在那么创建
#2.判断目标文件是否存在
if os.path.isfile(sourceFileName):
if not os.path.exists(strTo):
os.makedirs(strTo)
if not os.path.exists(targetFileName):
shutil.copyfile(sourceFileName, targetFileName)
if (os.path.exists(targetFileName) and (os.path.getsize(targetFileName) != os.path.getsize(sourceFileName))):
shutil.copyfile(sourceFileName, targetFileName)
if os.path.isdir(sourceFileName):
if os.path.exists(targetFileName):
shutil.rmtree(targetFileName)
shutil.copytree(sourceFileName, targetFileName)
@classmethod
def CopyTreeFromToWithFileType(cls, fileTypeArr, strFrom, strTo):
if os.path.isfile(strTo):
print("error")
return
if not os.path.exists(strTo):
os.makedirs(strTo)
CopyFileUtil.CopyTreeFromToWithFileTypeRecursion(fileTypeArr, strFrom, strTo)
@classmethod
def CopyTreeFromToWithFileTypeRecursion(cls, fileTypeArr, strFrom, strTo):
if os.path.isfile(strFrom):
strTempFileType = strFrom.split(".")[-1]
if strTempFileType in fileTypeArr:
shutil.copyfile(strFrom, strTo)
return
else:
if not os.listdir(strFrom):
return
for fileName in os.listdir(strFrom):
sourceFileName = os.path.join(strFrom, fileName)
targetFileName = os.path.join(strTo, fileName)
if os.path.isfile(sourceFileName):
strTempFileType = sourceFileName.split(".")[-1]
if strTempFileType in fileTypeArr:
shutil.copyfile(sourceFileName, targetFileName)
if os.path.isdir(sourceFileName):
if not os.path.exists(targetFileName):
os.makedirs(targetFileName)
CopyFileUtil.CopyTreeFromToWithFileTypeRecursion(fileTypeArr, sourceFileName, targetFileName)
CopyFileUtil.CopyTreeFromToWithFileType(["txt", "docx"], "H:/123", "H:/target")