python return empty list from function
<p>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.</p>

<pre><code>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)
</code></pre>

<p>This returns []</p>

<p>Thank you for the help</p>

<p>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):</p>

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

<p>If the <code>else</code> part is reached, then you recursively call <code>getfiles(path)</code>. 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 </p>

<pre><code>        myfiles.extend(getfiles(path))
</code></pre>

<hr>

<p>Additionally, you might want to check out <a href="https://docs.python.org/2/library/os.html" rel="nofollow"><code>os.walk</code></a>, as it does what it seems you're trying to do here.</p>

python