Does the file exist?

July 23, 2008

 

Python 2.5 has a cool any(iterable) function.  I needed to know if a file existed somewhere in a tree of files.  With any you can write something like the following:

    dirs = os.walk(os.path.abspath(''))  
    fileExists = any('testfile.txt' in x[2] for x in dirs)

Now the variable fileExists will be True if the file testfile.txt exists anywhere in the tree. 

two lines.  python is neat.

Leave a Reply