function to find the modification date of the project

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Jan 20 09:15:05 CET 2009


On Mon, 19 Jan 2009 20:22:55 -0700, Joe Strout wrote:

>> What if a curious user simple looks at a file with an editor and saves
>> it without change?
> 
> You can't do that, on the Mac at least...

Are you sure? That's a rather incredible claim. Surely you mean *some Mac 
editors* disable the Save command if the file hasn't been edited? Other 
editors may not, and POSIX command line tools certainly won't.

But that's a minor point.


> But really, this is NOT going to happen.  These users wouldn't even
> know how to open the app bundle to find the Python files.

Ah, the sorts of users who say "I looked in the system folder, and there 
was nothing there, so I deleted it". I know them well :-)


> Any comments on the functioning and platform-independence of the code?


I've developed a taste for writing that sort of function as a series of 
iterators. That's much like the Unix philosophy of piping data from one 
program to another. I'm sure I don't need to justify the benefits of Unix-
style tools, but if you don't like it, just combine the following two 
iterators into the lastModDate function that follows:


import os

def file_iter(dir='.', recurse=False):
    for root, dirs, files in os.walk(dir):
        if not recurse:
            del dirs[:]
        for file in files:
            yield os.path.join(root, file)

def filetype_iter(extensions=None, dir='.', recurse=False):
    if not extensions:
        extensions = ['']
    for file in file_iter(dir, recurse):
        if os.path.splitext(file)[1] in extensions:
            yield file

def lastModDate(dir=None, recurse=False):
    """Return the latest modification date of any Python source file."""
    if dir is None:
        dir = os.path.dirname(__file__)
    if dir == '':
        dir = '.'  # HACK, but appears necessary
    return max( (os.path.getmtime(name) for name 
        in filetype_iter(['.py'], dir, recurse)) )


It will raise a ValueError if there are no .py files in the directory, 
but that's easily changed.

Note also that I've changed lastModDate() to return the raw date stamp 
rather than a human readable string. The right place to covert to a human 
readable format is just before displaying it to a human being :)




-- 
Steven



More information about the Python-list mailing list