Search code examples
pythonpython-itertools

Python itertools lambda / best LINQ-alike approach in python


i am quite new to python, but i have quite some experience in C#. One of the things i love there is the set of tools that you get with the Linq-Framework. Therefore i was searching for some equivalent in Python, and as it seems there are a few attempts. Besides pynq, which i just did not get to work and seems to have died anyway, i found out that itertools has some options to get into that direction. but i still have problems to get it to work. what i want is a list of entries in a directory which are NOT directories. yes, i am sure there are plenty other and propably better ways to do this, but i want to solve this problem with itertools, as a similar problem could appear somewhere else, too.

import os, itertools

listing = os.listdir(".")
filteredfiles = itertools.ifilterfalse(lambda dirContent: os.path.isdir(dirContent), listing)
for f in filteredfiles:
    print "found file: " + f

This gives me an output of the complete content of the directory. If i replace ifilterfalse with ifilter, i get an empty list as an result.

i just can make a guess that it is just not working with a complex call to os.path.isdir(...), but i am not sure.

Can anyone give me an answer? Basically, as i said above, i just want some Linq-like possibility to filter Iterables. I dont like loops. They make me dizzy. ;-)


Solution

  • You need to create the full path name before checking:

    os.path.isdir(os.path.join(path, dirContent))