因此,这段代码最初是一个函数,在帮助下,我将其分解为两个单独的函数,但是我仍在努力使其工作。任何指导将不胜感激
# -------------------------------------------
# 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'
答案 0 :(得分:2)
您已将remove_directory
定义为采用单个位置arg,pathlist
,但是在全局范围内 not 却不采用变量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)
答案 1 :(得分:1)
在您的帖子中,您似乎正在呼叫remove_directory
,而没有根据需要传递列表,
将您的通话从remove_directory()
更改为remove_directory(dirs_to_delete)
答案 2 :(得分:1)
您需要将dirs_to_delete
传递给函数:
remove_directory(dirs_to_delete)
答案 3 :(得分:1)
调试:
TypeError: remove_directory() missing 1 required positional argument:
因为:
在这种情况下,功能remove_directory()
需要一个参数,也许dirs_to_delete
因此:
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(dirs_to_delete) # pass the list to the function here
答案 4 :(得分:0)
remove_directory函数需要参数pathlist
由于您没有为pathlist
添加默认值,因此调用remove_directory()
失败。
尝试:
def remove_directory(pathlist=[]):
for path in pathlist:
if check_directory(path):
shutil.rmtree(path)
print(colored('Found ' + path + ' removing', 'green'))
或在调用函数时提供列表:
remove_directory([])