On Mon, 29 Jun 2009 21:53:42 +0200, Christian Heimes wrote: >> I am curious about it being slow, though. Is there a faster way to get >> the contents of a directory than os.listdir() or is there a faster way >> to see if an element is in a list other than "x in y"? I believe >> 'which' will terminate once it finds any match, which mine does not, >> but that can be fixed by adding a break after the print. > > You don't need to get the entire directory content to see if a file > exists. The stat() syscall is much faster because it requires fewer disk > reads. On modern file systems stat() is a O(1) operation while "file" in > listdir() is a O(n) operation.
Apart from performance, stat() is more correct. readdir() (and Linux' getdents()) requires read permission on the directory, while stat() (and open() etc) only requires execute permission. On shared web (etc) servers, it's not uncommon for system directories (e.g. /usr/bin) to be "drwxr-x--x", as normal users shouldn't need to enumerate these directories. -- http://mail.python.org/mailman/listinfo/python-list