思路:
1、獲取該目錄下所有的文件名稱
2、過濾出要刪除的文件類型
3、通過篩選條件刪除要刪除的文件
偽代碼:
1、
def getFilePath(): #獲取該目錄下所有的文件名稱 rootPath=os.getcwd(); #獲取當前 workspace directory fileList=[] apkFileList=[] files = os.listdir(); for file in files: #獲取文件路徑 file_path = os.path.join(rootPath,file) fileList.append(file_path) if file_path.endswith(".apk"): apkFileList.append(file_path) # print(fileList) # print(apkFileList) return apkFileList
2、
# 遍歷apkFileList文件夾進行刪除舊的測試包 # for fileName in apkFileList: # print(fileName) if len(apkFileList)>2: for i in range(len(apkFileList)-2): os.remove(apkFileList[i])
3、整體功能代碼:(需求為:# 刪除舊的測試包,僅保留最新的兩個)
# 檢查刪除文件。僅存放最新的2個包,上次的和這次下載的包,以防這次的包有問題,還可以回退上一個包。 def deleteOldApkFile(): # 獲取該目錄下所有的文件名稱 rootPath=os.getcwd(); #獲取當前 workspace directory fileList=[] apkFileList=[] files = os.listdir(); for file in files: #獲取文件路徑 file_path = os.path.join(rootPath,file) fileList.append(file_path) if file_path.endswith(".apk"):# 過濾出指定后綴 .apk 的文件 apkFileList.append(file_path) # 遍歷apkFileList文件夾進行刪除舊的測試包 # for fileName in apkFileList: # print(fileName) if len(apkFileList)>2: for i in range(len(apkFileList)-2): os.remove(apkFileList[i])
【Reference】
—— Get “ rootPath=os.getcwd(); #獲取當前 workspace directory ”
—— Get 獲取文件列表與刪除文件