Getting previous file name
John Machin
sjmachin at lexicon.net
Tue Aug 8 17:39:20 EDT 2006
Miki wrote:
> Hello hj,
>
> > I have a small script here that goes to inside dir and sorts the file
> > by create date. I can return the create date but I don't know how to
> > find the name of that file...
> > I need file that is not latest but was created before the last file.
> > Any hints... I am newbiw python dude and still trying to figure out lot
> > of 'stuff'..
> >
> > ...
> Remember that Python comes with "battaries included":
> #!/usr/bin/env python
>
> from os import walk
> from os.path import getctime, join
>
> def cmp_file_by_ctime(file1, file2):
> return cmp(getctime(file1), getctime(file2))
If there are F files to be sorted, the OP's method requires F calls to
os.stat(), and C comparisons of a create time, where C is presumably
O(F*ln(F)) and is certainly >= (F-1).
Your method requires 2*C calls to os.path.getctime(). This might be
considered a little over the top -- you could be charged with "assault
and battery" :-)
>
> def walktree(path):
> file_list = []
> for root, dirs, files in walk(path):
> file_list += [join(root, file) for file in files]
>
> file_list.sort(cmp_file_by_ctime)
> return file_list[-2]
>
The OP gives every indication of wanting to examine all the files in
one directory, *NOT* walk over a directory tree.
Cheers,
John
More information about the Python-list
mailing list