新手问题 - 将函数一分为二

所以我是 python 的新手,我有一个需要分成两部分的函数。以前它是一个函数,但经过比我更了解的人的一些建议,我得到提示,我的函数做得太多了,我需要将其分解为两个独立的事情;所以我来了。


下面是分成两部分的代码。


我想知道我必须pathlist在这两个函数中都提到吗?


这应该做的是检查文件是否存在,然后如果它们存在,则运行第二个函数以删除实际目录。


def check_directory(pathslist):

    for path in pathslist:

        if os.path.exists(path) and os.path.isdir(path):

            remove_directory(pathslist)


dirs_to_delete = [

    'C:\MyDirectoryPath1',

    'C:\MyDirectoryPath2',

    'C:\MyDirectoryPath3'


 ]


def remove_directory(pathslist):

    for path in pathslist:

        if os.path.exists(path) and os.path.isdir(path):

            shutil.rmtree(path)

            print(colored('Found ' + path + ' removing', 'green'))


扬帆大鱼
浏览 173回答 1
1回答

心有法竹

不完全是。如果您将整个路径列表传递给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'))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python