Getting previous file name
John Machin
sjmachin at lexicon.net
Mon Aug 7 18:03:41 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 *
Lose that, and use ".st_ctime" instead of "[ST_CTIME]" below
>
> 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
> create_date_sces = os.stat(filename)[ST_CTIME]
Do you mean "secs" rather than "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
>
>
Cheers,
John
More information about the Python-list
mailing list