[英]How to get the most recent file
我是Python语言的新手,我需要编写一个代码,列出包含随机名称的文件的目录,例如:
JuniperAccessLog-独立-FCL_VPN-20120319-1110.gz
JuniperAccessLog-独立-FCL_VPN-20120321-1110.gz
我需要获取更新的文件
我试试这个,但没有成功。
import os
from datetime import datetime
t = datetime.now()
archive = t.strftime("JuniperAccessLog-standalone-FCL_VPN-%Y%m%d-%H*.gz")
file = os.popen(archive)
结果:
sh: JuniperAccessLog-standalone-FCL_VPN-20120320-10*.gz: command not found
有可能使用这个逻辑吗?
如果您想要最新的文件,您可以利用它们似乎按日期时间顺序排序的事实:
import os
logdir='.' # path to your log directory
logfiles = sorted([ f for f in os.listdir(logdir) if f.startswith('JuniperAccessLog-standalone-FCL_VPN')])
print "Most recent file = %s" % (logfiles[-1],)
你应该能够使用glob
模块获得你想要的东西:
def GetLatestArchive():
"Return the most recent JuniperAccessLog file for today's date."
import glob
from datetime import datetime
archive_format = datetime.now().strftime("JuniperAccessLog-standalone-FCL_VPN-%Y%m%d-%H*.gz")
archives = glob.glob(archive_format)
if len(archives) > 0:
# The files should come sorted, return the last one in the list.
return archives[-1]
else:
# No files were matched
return None
通过你的popen调用, glob
会做你正在尝试做的事情。
import os
import glob
from datetime import datetime
t = datetime.now()
archive = t.strftime("JuniperAccessLog-standalone-FCL_VPN-%Y%m%d-%H*.gz")
files = glob.glob(archive)
for f in files:
# do something with f
定义一个函数来解析文件名中的日期:
def date_from_path(path): m = re.match(r"JuniperAccessLog-standalone-FCL_VPN-(\\d+)-(\\d+).\\gz", path) return int(m.group(1)), int(m.group(2))
此函数使用您的日期和时间值可表示为整数的事实。
使用max
获取最新文件:
max(os.listdir(directory), key=date_from_path)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.