1 回答

TA贡献1866条经验 获得超5个赞
不完全是。如果您将整个路径列表传递给remove_directory,您将尝试删除每个路径列表,无论它是否存在,从而使您的 check_directory 函数变得不必要。我认为你的意思是在你的 check_directory 函数中只将存在的路径传递给 remove_directory:
def check_directory(pathslist):
for path in pathslist:
if os.path.exists(path) and os.path.isdir(path):
remove_directory(path)
dirs_to_delete = [
'C:\MyDirectoryPath1',
'C:\MyDirectoryPath2',
'C:\MyDirectoryPath3'
]
def remove_directory(path):
shutil.rmtree(path)
print(colored('Found ' + path + ' removing', 'green'))
您可能想尝试为您编写的每个函数写一条注释,描述它的作用。第二次使用单词“and”或附加动词时,暗示您最好将函数拆分为多个部分(这只是经验法则,而不是绝对的)。此外,您希望避免重复代码——如果您在两个单独的函数中有相同的代码行,这又是一个提示,您需要重新考虑您的设计。
编辑:正如评论中所指出的,您编写它的方式意味着调用check_directory将删除该目录(如果存在)。期望有人会check_directory出于不想删除它之外的原因而打电话似乎是合理的,并且您最好remove_directory打电话check_directory而不是相反:
def check_directory(path):
# returns true if path is an existing directory
return os.path.exists(path) and os.path.isdir(path)
def remove_directory(pathlist):
for path in pathlist:
if check_directory(path):
shutil.rmtree(path)
print(colored('Found ' + path + ' removing', 'green'))
添加回答
举报