是否可以使用startswith
打印最新文件?示例:以“ DOG”开头
import subprocess
import os
import glob
list_of_files = glob.iglob("C:\Users\Guest\Desktop\OJT\scanner\*")
latest_file =
print latest_file
答案 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。