Python find most recent File and get the size

2k views Asked by At

I am trying to get python to find the most recent file in a directory and get the file size. I have tried a couple different methods using "sorted" and "os.path" but nothing seems to work quite right. Here is sample code.

 filepath='/path/to/files'

 files = sorted([ 
    f for f in os.listdir(filepath) if f.startswith('spam')])


 print "Most recent file = %s" % (files[-1],)

 recent = files[-1]

 filesize = os.path.getsize(recent)

 #print "File size = %s" % (filesize)

This grabs the most recent file, but errors out when trying to find the size displaying it doesnt have a directory to search. So I went a different method like this.

import os,sys
from stat import *
from os.path import join

for (dirname, dirs, files) in os.walk('/path/to/file'):
    for filename in files:
            if filename.startswith('.tar.gz'):
                    thefile = os.path.join(dirname,filename)
                    size = os.path.getsize(thefile)
                    if size == 0
                    print "File %s has 0 data!" % thefile
                            exit 2
                    else print "File %s is good!" %thefile
                            exit 0

This one exits out with error invalid sytax on "size = 0"

Any help is much appreciated!

1

There are 1 answers

1
monkut On BEST ANSWER

os.path.getsize() needs the full path.

 filepath='/path/to/files'    
 files = sorted([ 
    f for f in os.listdir(filepath) if f.startswith('spam')])


 recent = files[-1]

 filesize = os.path.getsize(os.path.join(filepath, recent))