1. 程式人生 > >自己封裝的python3的一些檔案操作的腳手架

自己封裝的python3的一些檔案操作的腳手架

公司的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 #獲取檔案的md5 def getFileMd5(filePath): with open(filePath, 'rb') as f: content = f.read() hash = hashlib.md5() hash.update(content) return hash.hexdigest() #獲取一個資料夾裡的所有的檔案和該檔案對應的md5 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