【问题标题】:How to print latest file that starts with using python? [closed]如何打印以使用 python 开头的最新文件? [关闭]
【发布时间】:2018-09-25 12:52:02
【问题描述】:

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

import subprocess
import os
import glob

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

【问题讨论】:

  • 上次创建还是上次修改?
  • 包含目录,还是只包含文件?快捷方式呢?
  • 仅当文件名以某个日期时间字符串开头并且您确切知道要查找的字符串时。
  • @roganjosh:不,大多数流行的文件系统也存储“元数据”,例如创建时间、编辑时间和上次打开的时间戳。

标签: python file glob


【解决方案1】:

我不知道startswith 是什么意思,但试试这个:

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

【讨论】:

  • 这很有效,谢谢伙计
【解决方案2】:

对目录中的每个文件进行诸如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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 2012-09-16
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多