简体   繁体   English

python从函数返回空列表

[英]python return empty list from function

I am sorry to ask such a basic question but I am trying to learn python and don't understand why this does not work. 很抱歉提出这样一个基本问题,但我正在尝试学习python,但不明白为什么这行不通。 When I run this program on a directory it prints and empty list []. 当我在目录上运行该程序时,它会打印并清空列表[]。 I don't understand why. 我不明白为什么。 Can someone help? 有人可以帮忙吗? Python 3. Python 3。

import sys, os, 



def getfiles(currdir):
    myfiles = []
    for file in os.listdir(currdir):
         for file in os.listdir(currdir):
            path = os.path.join(currdir,file)
            if not os.path.isdir(path):
                myfiles.append(path)
            else:
                getfiles(path)
    return(myfiles)




if __name__ == '__main__':
    filedirectory = []
    filedirectory = getfiles(sys.argv[1])
    print(filedirectory)

This returns [] 返回[]

Thank you for the help 感谢您的帮助

If i understand you want to get all of the file names in a specific directory. 如果我了解您想获取特定目录中的所有文件名。 here is my code to do that : 这是我的代码来做到这一点:

Import os
AllFiles = []
AllFiles = os.listdir("your Directory")

listdir() return all files name in the specific directory. listdir()返回特定目录中的所有文件名。

Well, at least one case where your function will return an empty list, is if the topmost directory contains only directories. 好吧,至少在您的函数将返回一个空列表的情况下,如果最顶层的目录仅包含目录。 Here's your code (after removing the redundant loop): 这是您的代码(删除冗余循环后):

for file in os.listdir(currdir):
    path = os.path.join(currdir,file)
    if not os.path.isdir(path):
        myfiles.append(path)
    else:
        getfiles(path)

If the else part is reached, then you recursively call getfiles(path) . 如果到达else部分,则您递归调用getfiles(path) Unfortunately, you don't do anything with the result, and actually just throw it away. 不幸的是,您对结果不做任何事情,实际上只是将其丢弃。 You probably meant the last line to be something like 您可能是说最后一行是这样的

        myfiles.extend(getfiles(path))

Additionally, you might want to check out os.walk , as it does what it seems you're trying to do here. 此外,您可能想签出os.walk ,因为它似乎在这里尝试执行的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM