【解決】Python 刪除只讀文件/文件夾報錯:[WinError 5] 拒絕訪問。

1. 按

有時候我們使用shutil.rmtree()os.rmdir()os.remove()刪除文件時會報[WinError 5] 拒絕訪問的錯誤:
如使用os.remove()刪除當前文件夾下的'PackageCache\\[email protected]\\Tests\\Editor.meta'時提示

[WinError 5] 拒絕訪問。: ‘PackageCache\[email protected]\Tests\Editor.meta’

這個時候我們可以讓Python運行cmd命令強制刪除此文件:

import os
os.system('del "PackageCache\[email protected]\Tests\Editor.meta" /F')

關於使用CMD命令刪除文件或文件夾,可以參考:Windows CMD刪除文件或文件夾命令幫助

2. 實際運用

import os
import shutil


dirs = ['.idea', '.vs', 'Logs', 'obj']
files = ['.sln', '.csproj']

dirsCnt = 0
filesCnt = 0

def delWithCmd(path):
    try:
        if os.path.isfile(path):
            cmd = 'del "'+ path + '" /F'
            print(cmd)
            os.system(cmd)
    except Exception as e:
        print(e)


def deleteDir(dirPath):
    global dirsCnt
    global filesCnt
    for root, dirs, files in os.walk(dirPath, topdown=False):
        for name in files:
            try:
                filesCnt += 1
                filePath = os.path.join(root, name)
                print('file deleted', filesCnt, filePath)
                os.remove(filePath)
            except Exception as e:
                print(e)
                delWithCmd(filePath)
        for name in dirs:
            try:
                os.rmdir(os.path.join(root, name))
                dirsCnt += 1
            except Exception as e:
                print(e)
    os.rmdir(dirPath)

def delDir(dirPath):
    global dirsCnt
    shutil.rmtree(dirPath)
    dirsCnt += 1
    print('dir deleted', dirsCnt, dirPath)


def delFile(filePath):
    global filesCnt
    os.remove(filePath)
    filesCnt += 1
    print('file deleted', filesCnt, filePath)

def delete(path):
    try:
        if os.path.isfile(path):
            delFile(path)
        elif os.path.isdir(path):
            deleteDir(path)
    except Exception as e:
        print(e)

for proj in os.listdir():
    if not os.path.isdir(proj):
        continue
    os.chdir(proj)
    print(os.getcwd())
    for p in os.listdir():
        if os.path.isdir(p) and p in dirs:
            delete(p)
        elif os.path.isfile(p) and os.path.splitext(p)[1] in files:
            delete(p)
    libPath = 'Library'
    if os.path.exists(libPath) and os.path.isdir(libPath):
        os.chdir(libPath)
        for p in os.listdir():
            if p == 'LastSceneManagerSetup.txt':
                continue
            delete(p)
        os.chdir('..')
    os.chdir('..')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章