公司的win和mac客户端打包升级的脚本以前是自己用批处理、shell、c++写的,是个大杂烩,适应新的需求有些吃力了,为了适应新的需求和方便扩展,我用python把原来的脚本重构了一下,其中写了文件操作的一些函数,如下:
import os
import shutil
import hashlib
import stat
def findMyFileDir (dirPath, findFile) :
files = []
dirs = []
for root, dirs, files in os.walk(dirPath, topdown=False ):
for file in files:
if file == findFile:
return root
for dir in dirs:
findMyFileDir(os.path.join(root, dir), findFile)
def createDir (dirPath) :
os.makedirs(dirPath, exist_ok=True )
def delFile (filePath) :
if os.path.exists(filePath):
os.remove(filePath)
def delDir (dir) :
if (os.path.isdir(dir)):
for f in os.listdir(dir):
delDir(os.path.join(dir, f))
if (os.path.exists(dir)):
os.rmdir(dir)
else :
if (os.path.exists(dir)):
os.remove(dir)
def copyFile (sourceFilePath, destFilePath) :
if not (os.path.exists(sourceFilePath)):
return False
if os.path.exists(destFilePath):
if getFileMd5(sourceFilePath) == getFileMd5(destFilePath):
return True
else :
os.remove(destFilePath)
destFileDir = os.path.dirname(destFilePath)
os.makedirs(destFileDir, exist_ok=True )
if not (shutil.copyfile(sourceFilePath, destFilePath, follow_symlinks=False )):
return False
return True
def copyDir (sourceDir, destDir) :
if not (os.path.exists(sourceDir)):
return False
if os.path.exists(destDir):
shutil.rmtree(destDir)
if not (shutil.copytree(sourceDir, destDir, symlinks=True )):
return False
return True
def getFileMd5 (filePath) :
with open(filePath, 'rb' ) as f:
content = f.read()
hash = hashlib.md5()
hash.update(content)
return hash.hexdigest()
def dirList (dirPath) :
listDict = {}
files = []
dirs = []
for root, dirs, files in os.walk(dirPath, topdown=False , followlinks=True ):
for file in files:
filePath = os.path.join(root, file)
listDict[os.path.relpath(filePath, dirPath).replace(
'\\' , '/' )] = getFileMd5(filePath)
for dir in dirs:
dirList(os.path.join(root, dir))
return listDict
def readLineForFile (filePath) :
f = open(filePath, 'r' )
lines = f.readlines()
f.close()
newLines = []
for line in lines:
line = line.replace('\n' , '' ).strip()
if line:
newLines.append(line)
return newLines