使用python刪除指定文件


 

思路:

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】

1、Python當前文件路徑與文件夾刪除操作 

—— Get  “ rootPath=os.getcwd(); #獲取當前 workspace directory ”

2、利用python刪除指定文件或文件夾 

—— Get 獲取文件列表與刪除文件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM