import os,re,json
import shutil
import traceback
#@author Eikoh
#@time 2020/9/1
#字符串常用的就replace split
#数组常用的就append
#将路径对应文件夹设定成空文件夹
def genEmptyFolder(url):
if os.path.exists(url):
deleteDir(url)
print("清空[%s]"%url)
else:
os.makedirs(url)
#判断obj中是否有对应key
def hasKey(obj,key):
if key in obj.keys():
return True
return False
#打开文件文本形式读取所有文本
def getContent(fileUrl):
if not os.path.exists(fileUrl):
return ""
readFile = open(fileUrl, mode='r',encoding='UTF-8')
# 转成list
f_list = readFile.readlines()
content = ""
# 拿到所有内容 content
for index in range(len(f_list)):
content = content + f_list[index]
readFile.close()
return content
def copyFile(src,dst):
if os.path.isdir(src):
#是文件夹,遍历
for filename in os.listdir(src):
copyFile(src + "/" + filename,dst + "/" + filename)
else:
dirPath = getDirPath(dst,False)
if not os.path.exists(dirPath):
os.makedirs(dirPath)
shutil.copy(src,dirPath)
def getDirPath(path,isFolder):
if isFolder:
return path
else:
realPath = ''
pathArr = path.split("/")
if(len(pathArr) == 1):
pathArr = path.split("\\")
for i in range(len(pathArr) - 1):
realPath = os.path.join(realPath,pathArr[i])
return realPath
#保存文本到文件,覆盖写入
def saveContent(fileUrl,content):
outFile = open(fileUrl, mode='w+',encoding='UTF-8')
outFile.write(content)
outFile.close()
#清空文件夹
def deleteDir(current_path):
clearDir(current_path)
os.makedirs(current_path)
#清空文件夹下所有文件
def clearDir(dirPath):
if os.path.isdir(dirPath):
try:
for root, dirs, files in os.walk(dirPath):
for name in files:
# delete the log and test result
del_file = os.path.join(root, name)
os.remove(del_file)
#print('remove file[%s] successfully' % del_file)
shutil.rmtree(dirPath)
print('删除文件夹[%s] 成功' % dirPath)
except Exception:
traceback.print_exc()
#正则匹配,全匹配
def match(reg,str):
matchArr = re.findall( reg, str, re.M|re.I)
if matchArr:
return matchArr
return []
def jsonEncode(obj):
return json.dumps(obj)
def jsonDecode(str):
return json.loads(str)
def quickSortByKey(aList,key,bigFirst):
if len(aList) <= 1:
return aList
tItem = aList[len(aList)-1]
pivot = -1
for index,item in enumerate(aList):
if (not bigFirst and item[key] < tItem[key]) or (bigFirst and item[key] > tItem[key]):
pivot += 1
aList[pivot], aList[index] = aList[index], aList[pivot]
pivot = pivot + 1
aList[pivot], aList[index] = aList[index], aList[pivot]
left = quickSortByKey(aList[:pivot],key,bigFirst)
middle = [aList[pivot]]
right = quickSortByKey(aList[pivot+1:],key,bigFirst)
newList = left+middle+right
return newList