我正在尝试从目录树中删除旧的SVN文件。 shutil.rmtree
和os.unlink
提升WindowsError
,因为该脚本无权删除它们。我怎么能解决这个问题?
这是脚本:
# 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 :(得分:4)
Subversion通常会使所有.svn
目录(以及其中的所有内容)都受到保护。可能在删除文件之前必须先删除写保护。
我不确定如何使用Windows做到最好,但您应该能够将os.chmod()
与stat.S_IWRITE
标志一起使用。可能你必须遍历.svn
目录中的所有文件,并使它们都可以单独写入。
答案 1 :(得分:3)
要递归删除所有.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)