简体   繁体   中英

Python find most recent File and get the size

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!

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM