[英]Python find most recent File and get the size
我正在尝试让python在目录中查找最新文件并获取文件大小。 我已经尝试过使用“ sorted”和“ os.path”的几种不同方法,但是似乎没有什么工作很正确。 这是示例代码。
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)
这会获取最新的文件,但是在尝试查找显示的文件大小时出错,没有要搜索的目录。 所以我采用了另一种这样的方法。
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
此错误以“ size = 0”上的错误无效语法退出
任何帮助深表感谢!
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.