[Tutor] getting the last file in a folder (reliably)

Steven D'Aprano steve at pearwood.info
Mon Mar 21 23:44:59 CET 2011

Pete O'Connell wrote:
> Hi I have some code which works nine times out of ten. 

Today. Next week it might work zero times out of ten. Your result is a 
pure accident of the order that the files are created. When you call 
os.listdir(), you don't get the files in any specific order. The order 
you receive is the order that they happen to be stored by the file 
system, which is essentially arbitrary.

So you take this arbitrary list, walk through it in order skipping some 
files, and when you hit the last file, you go on to the next step. But 
there's no guarantee which that last file will be.

A better way is to take the file names from os.listdir, remove the ones 
you don't care about, and then sort the remaining ones, then take the 
last one:

files = os.listdir('.')
# filter out backups and autosave files
files = [f for f in files if not (f.endswith('~') or
the_file_name = files[-1]

should work, although you might need a bit more work on the sorting.

One last comment:

> def openNewestCompCommandLine():

Your function is called *open* newest command line. How do you open a 
command line? Seems like a misleading name to me. But then, instead of
opening the file, you "nuke" it instead:

>     os.system("nuke "  + theFullPath)

Oh my, I can see this being *very* entertaining in the future...


More information about the Tutor mailing list