1. 程式人生 > >python3的一些文件操作的腳手架

python3的一些文件操作的腳手架

makedirs 查找文件 with true clas std top new ted

用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

python3的一些文件操作的腳手架