2010-06-11 94 views
3

我想從目錄樹中刪除舊的SVN文件。 shutil.rmtreeos.unlink舉起WindowsError s,因爲腳本沒有權限刪除它們。我該如何解決這個問題?Python腳本刪除舊的SVN文件缺乏權限

下面是腳本:

# Delete all files of a certain type from a direcotry 

import os 
import shutil 

dir = "c:\\" 

verbosity = 0; 

def printCleanMsg(dir_path): 
    if verbosity: 
     print "Cleaning %s\n" % dir_path 

def cleandir(dir_path): 
    printCleanMsg(dir_path) 
    toDelete = [] 
    dirwalk = os.walk(dir_path) 
    for root, dirs, files in dirwalk: 
     printCleanMsg(root) 
     toDelete.extend([root + os.sep + dir for dir in dirs if '.svn' == dir]) 
     toDelete.extend([root + os.sep + file for file in files if 'svn' in file]) 

    print "Items to be deleted:" 
    for candidate in toDelete: 
     print candidate 
    print "Delete all %d items? [y|n]" % len(toDelete) 

    choice = raw_input() 

    if choice == 'y': 
     deleted = 0 
     for filedir in toDelete: 
      if os.path.exists(filedir): # could have been deleted already by rmtree 
       try: 
        if os.path.isdir(filedir): 
         shutil.rmtree(filedir) 
        else: 
         os.unlink(filedir) 
        deleted += 1 
       except WindowsError: 
        print "WindowsError: Couldn't delete '%s'" % filedir 

    print "\nDeleted %d/%d files." % (deleted, len(toDelete)) 
    exit() 

if __name__ == "__main__": 
    cleandir(dir) 

不是一個單一的文件能夠被刪除。我究竟做錯了什麼?

+0

只是爲了掩蓋顯而易見的問題:你確定這是一個權限問題嗎? – 2010-06-11 03:14:41

+0

是的。它說:'WindowsError:[錯誤5]訪問被拒絕:'dir'' – 2010-06-11 03:25:10

回答

4

Subversion通常會使所有的.svn目錄(以及其中的所有內容)都被寫保護。在刪除文件之前,可能必須刪除寫保護。

我不太確定如何在Windows上做到最好,但是您應該能夠使用os.chmod()stat.S_IWRITE標誌。可能您必須遍歷.svn目錄中的所有文件,並使它們全部可單獨寫入。

0

要遞歸刪除所有.svn我使用此腳本。可能會幫助某人。

import os, shutil, stat 

def del_evenReadonly(action, name, exc): 
    os.chmod(name, stat.S_IWRITE) 
    os.remove(name) 

for root, subFolders, files in os.walk(os.getcwd()): 
    if '.svn' in subFolders: 
     shutil.rmtree(root+'\.svn',onerror=del_evenReadonly)