2012-07-24 191 views
4

我正在爲其創建一些子目錄的測試用例。但是,我似乎沒有權限將其刪除。我的UA是一個管理員帳戶(Windows XP)。無法使用os.remove刪除文件夾(WindowsError:[錯誤5]訪問被拒絕:'c:/ temp/New Folder')

我第一次嘗試:

folder="c:/temp/" 
for dir in os.listdir(folder): 
    os.remove(folder+dir) 

然後

folder="c:/temp/" 
os.remove(folder+"New Folder") 

,因爲我敢肯定, 「新建文件夾」 是空的。然而,在所有情況下,我得到:

Traceback (most recent call last): 
    File "<string>", line 3, in <module> 
WindowsError: [Error 5] Access is denied: 'c:/temp/New Folder' 

有人知道發生了什麼問題嗎?

回答

14

os.remove需要文件路徑,並提出了OSError如果路徑是目錄

嘗試os.rmdir(folder+'New Folder')

哪樣:

Remove (delete) the directory path. Only works when the directory is empty, otherwise, OSError is raised.

製作路徑也是安全使用os.path.join

os.path.join("c:\\", "temp", "new folder") 
10

嘗試內置shutil模塊

shutil.rmtree(folder+"New Folder") 

這遞歸地刪除一個目錄,即使它有內容。

+0

酷!這就是我需要的!謝謝! – 2012-08-05 19:29:54

+0

如果它的svn結帳文件夾沒有工作... – 2016-05-20 04:32:07

4

U可以使用Shutil模塊刪除該目錄及其子文件夾

import os 
import shutil 

for dir in os.listdir(folder): 
    shutil.rmtree(os.path.join(folder,dir)) 
5

os.remove()僅適用於文件。它不適用於目錄。按照documentation

os.remove(path) Remove (delete) the file path. If path is a directory, OSError is raised; see rmdir() below to remove a directory. This is identical to the unlink() function documented below. On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.

使用os.removedir()對目錄

+1

os.rmdir()將刪除一個空目錄。 shutil.rmtree()將刪除一個目錄及其所有內容。 – sparrow 2016-07-29 18:55:18

-1

文件是隻讀模式,以便通過os.chmod()功能更改文件權限,然後用os.remove()嘗試。

例:

更改文件權限0777,然後刪除該文件。

os.chmod(filePath, 0777) 
os.remove(filePath) 
相關問題