Getting previous file name
Larry Bates
larry.bates at websafe.com
Mon Aug 7 17:28:58 EDT 2006
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 *
>
> def walktree(path):
> test1 = []
> for f in os.listdir(path):
> filename = os.path.join(path, f)
> create_date_sces = os.stat(filename)[ST_CTIME]
> create_date = time.strftime("%Y%m%d%H%M%S",
> time.localtime(create_date_sces))
> print create_date, " ....." , f
> test1.append(create_date)
> test1.sort()
> print test1
> return test1[-2]
>
>
> if __name__ == '__main__':
> path = '\\\\srv12\\c$\\backup\\my_folder\\'
> prev_file = walktree(path)
> print "Previous back file is ", prev_file
>
>
> Thank you,
> hj
>
Just some quick ideas (not tested):
change test1.append(create_date) to test1.append((create_date, filename))
that way the filename will tag along during the sorting as a tuple in
the test1 list.
You will also need to change prev_file = walktree(path) to
create_date, prev_file = walktree(path)
Note: Your script can't handle the situation where there are zero or
one file(s) in the path (you should probably put in some code for those
edge cases).
-Larry Bates
More information about the Python-list
mailing list