【发布时间】:2019-07-22 06:02:45
【问题描述】:
我正在构建一个 Python 脚本来从任意一组子目录中选择和打开文件。为此,我正在构建一个带有 for 循环的函数,以列出一个目录中的所有文件,以及该目录中所有子目录的另一个列表。然后另一个 for 循环通过递归调用相同的函数来更改每个子目录。我在调试模式下反复执行了这个函数,并非常仔细地观察了每个变量,因为它一步一步地变化。
我完全不知所措,因为每个循环都运行了一点点,但它没有完成就退出了。通常在编程中,事情完全可以工作或根本不工作,但它们很少只工作一半。两个循环都这样做,当对函数的第二次调用退出时,它不会返回第一次调用以完成第二次循环,而是完全退出对函数的所有调用。这是代码,非常感谢您的帮助:
def descend(directory, depth, dive=-1): # dive=-1 before we have touched the surface
global choices # list of files to be chosen from later
os.chdir(directory) # change to target directory
dirlist = [] # empty the list of directories within the directory
baseList = os.listdir(directory) # list of all files and directories
if dive < depth: # depth corresponds to the levels of sub-directories to be searched
dive += 1 # effectively starts at 0
fileIndex=0 # index as we step through the baseList
for x in baseList: # why doesn't this loop complete?
if os.path.isfile(x) == True: # if it's a regular file
path = directory + '/' + baseList.pop(fileIndex) # create its full path
choices.append(path) # and add that to our list of choices
elif os.path.isdir(x) == True: # if it's a directory
dirlist.append(baseList.pop(fileIndex)) # add to list of directories to recursively search
fileIndex += 1 # add 1 to the file index
for x in dirlist: # for each item in the list of directories
nextdir = directory + '/' + dirlist.pop() # make a variable of its full path
descend(nextdir, depth, dive) # pass that back to this function and repeat
我什至尝试过一些愚蠢的解决方案,例如将 if len(baseList) != 0: continue 添加到循环的底部,这不应该被告知两次,但这对他们中的任何一个都没有帮助。我完全被难住了。
【问题讨论】:
-
不要从您正在迭代的列表中删除元素。我不知道你为什么在这里使用
pop,但我认为修复应该像用baseList[fileIndex](或x)替换它一样简单。 -
@Aves 您只想获取
baseList[fileIndex],而不是像baseList.pop(fileIndex)一样将其从列表中删除。但无论如何,你不需要管理这个fileIndex:只需做path = directory + '/' + x -
嗯,这很快......我以为我一开始就是这样,需要改变它来解决问题,但现在我用 x 和它替换了 .pop() 函数似乎工作正常。
标签: python loops for-loop recursion