Graham Fawcett fawcett at teksavvy.com
Tue Sep 9 01:47:28 CEST 2003

Hari wrote:

>I have question regarding os.listdir()
>I wanted to know if this is a reliable way to check for files added to
>a directory??
>files = os.lisdir(path)
>currentlen = len(files)
>// directory modified 
>files = os.listdor(path)
>newlen = len(files)
>then the files in the range (currentlen -1) to (newlen -1) are all the
>files added to the directory.
>What I wanted to know was, is it guaranteed that between 2 calls
>os.listdir any files added to the directory are appended and the
>earlier order is maintained?

Unless the documentation for os.listdir specifies such behaviour 
explicitly, you should assume the answer is /no/. There are many 
Pythons, running on many platforms; don't assume that they all share 
identical unspecified behaviour.

There's no need for such sequence guarantees, though. It's probably not 
the most efficient but here's a way to do it:

    import os
    import time

    somedir = '/tmp'
    snapshot1 = os.listdir(somedir)
    snapshot2 = os.listdir(somedir)

    newfiles = [f for f in snapshot2 if not f in snapshot1]

Pretty efficient, really: that's an O(n) comparison if I remember my 
Python internals correctly. Which I don't, so don't trust my word for 
it. ;-)

-- Graham

More information about the Python-list mailing list