将路径列表传递给另一个函数

2024-09-28 01:28:53 发布

您现在位置:Python中文网/ 问答频道 /正文

所以这段代码最初是一个函数,在我的帮助下,我把它分成了两个独立的函数,但我仍然在努力让它工作。任何指导都将不胜感激

# -------------------------------------------
# Checks to see if listed folders exists and then deletes
# -------------------------------------------


def check_directory(path):
    # returns true if path is an existing directory
    return os.path.exists(path) and os.path.isdir(path)


dirs_to_delete = [
    'C:\Folder Here',
    'C:\Folder Here1',
    'C:\Folder Here2',
    'C:\Folder Here3'

 ]


def remove_directory(pathlist):
    for path in pathlist:
        if check_directory(path):
            shutil.rmtree(path)
            print(colored('Found ' + path + ' removing', 'green'))

我调用这个函数

remove_directory()     #Checks and Removes directories listed above

运行时出现以下错误

remove_directory()  #Checks and Removes directories listed above
TypeError: remove_directory() missing 1 required positional argument: 'pathlist'

Tags: andtopath函数ifosdefcheck
3条回答

在您的帖子中,似乎您正在调用remove_directory,但没有按要求传递列表,
将呼叫改为remove_directory()remove_directory(dirs_to_delete)

您需要将dirs_to_delete传递给函数:

remove_directory(dirs_to_delete)

您已经定义了remove_directory来获取单个位置参数pathlist,但是,它在全局范围内不获取变量pathlist的值:

s = 100

def print_val(s):
    print(s)

# I have not given it a positional arg, so s isn't defined
print_val()
# raises TypeError because the scope inside the function
# doesn't know what s is

# Now i give it that value
print_val(s)
# 100

所以对于你的问题,你需要通过arg

# This is how you call the function in your script
remove_directory(pathlist)

相关问题 更多 >

    热门问题