Getting previous file name

Hitesh hitesh287 at gmail.com
Tue Aug 8 14:34:12 EDT 2006



John Machin wrote:
> Hitesh wrote:
> > Hi,
> >
> > 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'..
> >
> >
> > import os, time, sys
> > from stat import *
>
> Lose that, and use ".st_ctime" instead of "[ST_CTIME]" below
>

Not sure how to do that so I am going to leave it alone.

> >
> > def walktree(path):
>
> This function name is rather misleading. The function examines only the
> entries in the nominated path. If any of those entries are directories,
> it doesn't examine their contents.
>
> >     test1 = []
> >     for f in os.listdir(path):
> >             filename = os.path.join(path, f)
>
> os.listdir() gives you directories etc as well as files. Import
> os.path, and add something like this:
>
>         if not os.path.isfile(filename):
>             print "*** Not a file:", repr(filename)
>             continue
>

This is cool stuff. I am stuffing this inside my script.


> >             create_date_sces = os.stat(filename)[ST_CTIME]
>
> Do you mean "secs" rather than "sces"?

Yes I mean secs not sces.

>

> >             create_date = time.strftime("%Y%m%d%H%M%S",
> > time.localtime(create_date_sces))
> >             print create_date, " ....." , f
> >             test1.append(create_date)
>
> Answer to your main question: change that to
> test1.append((create_date, filename))
> and see what happens.
>
> >     test1.sort()
>
> If there is any chance that multiple files can be created inside 1
> second, you have a problem -- even turning on float results by using
> os.stat_float_times(True) (and changing "[ST_CTIME]" to ".st_ctime")
> doesn't help; the Windows result appears to be no finer than 1 second
> granularity. The pywin32 package may provide a solution.
>
> >     print test1
> >     return test1[-2]
> >
> >
> > if __name__ == '__main__':
> > 	path = '\\\\srv12\\c$\\backup\\my_folder\\'
>
> (1) Use raw strings. (2) You don't need the '\' on the end.
> E.g.
>     path = r'\\srv12\c$\backup\my_folder'
>
> > 	prev_file = walktree(path)
> > 	print "Previous back file is ", prev_file
> > 


Thank you 
hj




More information about the Python-list mailing list