2013-04-24 76 views
3

我想刪除一個目錄,但是當我運行代碼時,它給了Windows錯誤5:訪問被拒絕。這裏是我的代碼:在Release文件夾中,有一個名爲OD的文件夾。Windows錯誤5:嘗試刪除Windows中的目錄時訪問被拒絕

if os.path.exists(os.path.join(get_path_for_output,'Release')): 
     shutil.rmtree(os.path.join(get_path_for_output,'Release')) 

錯誤是這樣的:

WindowsError: [Error 5] Access is denied: 'C:\\Users\\marahama\\Desktop\\Abdur_Release\\Release\\OD\\automations\\GEM\\FMS_adapter.py' 
+5

有人在某處使用該文件。也許這就是你運行的文件? – zmbq 2013-04-24 05:21:53

+0

沒有。我認爲。我已經檢查過了。 – 2013-04-24 05:25:15

+0

關閉所有程序和cmd提示窗口,然後再試一次,有東西有文件鎖定。 – Ardesco 2013-04-24 05:26:28

回答

0
takeown /F C:\<dir> /R /A 
icacls C:\<dir> /grant administrators:F /t 

授予所有權管理員和充分控制,管理員,如果你的用戶是管理員。

1

我使用pydev。我的解決方案是:

  1. 停止Eclipse。
  2. 啓動Eclipse與選項以管理員身份運行
4

這是由於該文件的權限問題。

您需要具有在該文件上執行該任務的權限。

要獲得與文件相關聯的權限,使用os.stat(fileName)

可以明確檢查寫權限使用os.access(fileName, os.W_OK)

然後將該文件,更改權限,os.chmod(fileName,permissionNumeric)

例:os.chmod(fileName, '0777')

要更改正在執行當前文件的權限, 使用os.chmod(__file__, '0777')

+0

我得到了'TypeError:一個整數是必需的'並且將''0777''更改爲'0777'對我有用。 – HunterrJ 2017-12-14 05:47:46

0

爲了改變位於文件「C:」你必須擁有管理員權限, 你

#!python 
# coding: utf-8 
import sys 
import ctypes 

def run_as_admin(argv=None, debug=False): 
    shell32 = ctypes.windll.shell32 
    if argv is None and shell32.IsUserAnAdmin(): 
     return True 

    if argv is None: 
     argv = sys.argv 
    if hasattr(sys, '_MEIPASS'): 
     # Support pyinstaller wrapped program. 
     arguments = map(unicode, argv[1:]) 
    else: 
     arguments = map(unicode, argv) 
    argument_line = u' '.join(arguments) 
    executable = unicode(sys.executable) 
    if debug: 
     print 'Command line: ', executable, argument_line 
    ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1) 
    if int(ret) <= 32: 
     return False 
    return None 


if __name__ == '__main__': 
    ret = run_as_admin() 
    if ret is True: 
     print 'I have admin privilege.' 
     raw_input('Press ENTER to exit.') 
    elif ret is None: 
     print 'I am elevating to admin privilege.' 
     raw_input('Press ENTER to exit.') 
    else: 
     print 'Error(ret=%d): cannot elevate privilege.' % (ret,) 

代碼摘自:啓動腳本或而這樣做,例如前可以讓他們How to run python script with elevated privilege on windows

腳本作者:Gary Lee

相關問題