简体   繁体   中英

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. When I run this program on a directory it prints and empty list []. I don't understand why. Can someone help? 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.

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) . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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