如何打印以python开头的最新文件?

时间:2018-09-25 12:52:02

标签: python file glob

是否可以使用startswith打印最新文件?示例:以“ DOG”开头

import subprocess
import os
import glob

list_of_files = glob.iglob("C:\Users\Guest\Desktop\OJT\scanner\*")
latest_file = 
print latest_file

2 个答案:

答案 0 :(得分:3)

我不知道您所说的startswith是什么意思,但是请尝试以下操作:

files = glob.iglob(r"C:\Users\Guest\Desktop\OJT\scanner\*")
latest_file = max(files, key=os.path.getctime)

答案 1 :(得分:0)

在目录中的每个文件上进行诸如os.path.getctime之类的系统调用可能既缓慢又昂贵。在一次调用中使用os.scandir来获取目录中文件的所有信息的效率要高很多倍,因为在调用过程中随时可以使用它来获取目录列表。

import os
directory = r"C:\Users\Guest\Desktop\OJT\scanner"
latest_file = max(os.scandir(directory), key=lambda f: f.stat().ST_MTIME).name

有关详细信息,请阅读PEP-471