Python获取最新目录并解压缩

yus*_*sof 0 python

我正在编写一个压缩的python脚本.我设法提取文件,并在其中一个子目录中有更多的压缩文件.我希望我的脚本找到可用的最新压缩文件并将其解压缩.

我将脚本分成不同的部分进行故障排除.下面是第二部分,其中包含我遇到问题的部分:

import os
import time
import glob

path = "/home/user/scripts/logs/old" #logs was the original compressed file. Old is
#where the other compressed files are.

for file in glob.glob( os.path.join(path, '*.tar.gz') ):
    filename = os.path.basename(file)
    statinfo = os.stat(file)
    print file + "  " + time.ctime(os.path.getmtime(file))
Run Code Online (Sandbox Code Playgroud)

该脚本只列出文件名,然后列出上次修改压缩文件的时间戳.如何告诉python获取上次修改文件的名称,以便继续解压缩?

Sha*_*ger 5

如果你在一个名为变量的文件列表中(通过任何方式,例如globbing)files_to_check,只需使用maxwith os.path.getmtime作为键:

files_to_check = glob.glob(os.path.join(path, '*.tar.gz'))
most_recent_file = max(files_to_check, key=os.path.getmtime)
Run Code Online (Sandbox Code Playgroud)

  • 好的答案,优雅的关键参数使用! (2认同)