1

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

gelse
  • 25
  • 1
  • 5
  • 1
    Your current code works fine for me, with `ifilterfalse` it only displays files, with `ifilter` it only displays directories. – Andrew Clark Oct 18 '12 at 20:15
  • 2
    I don't love loops either, but note that Python has more convenient syntax than function call + lambda for certain common operations. See [Python's list comprehension vs .NET LINQ](http://stackoverflow.com/q/3925093/395760). Also, lambdas which just pass arguments on are redundant: `filter(os.path.isdir, listing)` works and is superior. –  Oct 18 '12 at 20:15
  • @F.J interesting... Is it possible that you're using windows? See Iliyan's answer below. – gelse Oct 19 '12 at 07:49
  • @delnan thanks for the link, gives me a huge step forward on understanding python. :D – gelse Oct 19 '12 at 07:50

1 Answers1

1

You need to create the full path name before checking:

os.path.isdir(os.path.join(path, dirContent))
Iliyan Bobev
  • 3,070
  • 2
  • 20
  • 24