如何获取最新文件

时间:2012-03-20 13:50:26

标签: python 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

有可能使用这种逻辑吗?

4 个答案:

答案 0 :(得分:8)

如果您想要最新的文件,可以利用它们似乎按日期时间顺序排序的事实:

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

答案 1 :(得分:2)

您应该能够使用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

答案 2 :(得分:0)

glob会根据您的popen电话执行您要执行的操作。

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

答案 3 :(得分:0)

  1. 定义一个函数来解析文件名中的日期:

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

    此函数使用的事实是您的日期和时间值可以表示为整数。

  2. 使用max获取最新文件:

    max(os.listdir(directory), key=date_from_path)