简体   繁体   English

Python查找最新文件并获取大小

[英]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. 我正在尝试让python在目录中查找最新文件并获取文件大小。 I have tried a couple different methods using "sorted" and "os.path" but nothing seems to work quite right. 我已经尝试过使用“ sorted”和“ os.path”的几种不同方法,但是似乎没有什么工作很正确。 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" 此错误以“ size = 0”上的错误无效语法退出

Any help is much appreciated! 任何帮助深表感谢!

os.path.getsize() needs the full path. os.path.getsize()需要完整路径。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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