[英]How to get the most recent file
i am newbie in Python language and i need write a code that list directory that contains files with random names, for example: 我是Python语言的新手,我需要编写一个代码,列出包含随机名称的文件的目录,例如:
JuniperAccessLog-standalone-FCL_VPN-20120319-1110.gz
JuniperAccessLog-独立-FCL_VPN-20120319-1110.gz
JuniperAccessLog-standalone-FCL_VPN-20120321-1110.gzJuniperAccessLog-独立-FCL_VPN-20120321-1110.gz
I need get the more recent file 我需要获取更新的文件
I try this, but without success. 我试试这个,但没有成功。
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)
Result: 结果:
sh: JuniperAccessLog-standalone-FCL_VPN-20120320-10*.gz: command not found
have a possibility the use this logic ? 有可能使用这个逻辑吗?
If you want the most recent file, you could take advantage of the fact that they appear to sort into date time order: 如果您想要最新的文件,您可以利用它们似乎按日期时间顺序排序的事实:
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],)
You should be able to get what you want using the glob
module: 你应该能够使用
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
glob
will do what you are trying to do with with your popen call. 通过你的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
Define a function to parse the date out of the filename: 定义一个函数来解析文件名中的日期:
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))
This function uses the fact that your date and time values are representable as integers. 此函数使用您的日期和时间值可表示为整数的事实。
Use max
to get the most recent file: 使用
max
获取最新文件:
max(os.listdir(directory), key=date_from_path)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.