Hi. I just started python programming tonight and am trying to use good practices such as list comprehensions etc.

However, I'm trying to get a list of all files in a directory (and subdirectories) and only add the filename to my list if its extension matches one of the extensions in my list.

Please help me solve my error:

def ListMyFiles():
    TotalList=[]
    fileEXTlist=".txt"

    TotalList=[filenames for root, dirnames, filenames in os.walk(os.path.join("G:","00Test"),topdown=True) if os.path.splitext(filenames)[1] in fileEXTlist]

    return TotalList

Error:

Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    ListMyFiles()
  File "C:\Documents and Settings\user\Desktop\MediaApp1.py", line 65, in ListMyFiles
    TotalList=[filenames for root, dirnames, filenames in os.walk(os.path.join("G:","00Test"),topdown=True) if os.path.splitext(filenames)[1] in fileEXTlist]
  File "C:\Python26\lib\ntpath.py", line 190, in splitext
    return genericpath._splitext(p, sep, altsep, extsep)
  File "C:\Python26\lib\genericpath.py", line 91, in _splitext
    sepIndex = p.rfind(sep)
AttributeError: 'list' object has no attribute 'rfind'

Solved this one with some tinkering.

In my example I was passing a list to os.path.splitext instead of further narrowing it down to a filename:

new code works below:

TotalList=[filez for root, dirnames, filenames in os.walk("G:\\00Test",topdown=True) for filez in filenames if os.path.splitext(filez)[1] in fileEXTlist]

Works perfectly!

Comments
pretty smart stuff
This question has already been answered. Start a new discussion instead.