简体   繁体   中英

How can I get the most recent file from a directory?

cached_folder = os.path.expandvars(r'%APPDATA%\Microsoft\Windows\Themes\CachedFiles\*')
list_of_files = glob.glob(cached_folder)
latest_file = max(list_of_files, key=os.path.getctime)

I just want the path of the most recent file in CachedFiles although this doesn't work and list_of_files is an empty list.

What am I doing wrong here?

The code below (essentially wrapping your code) worked for me. You may have an empty %APPDATA%\Microsoft\Windows\Themes\CachedFiles .

#!/usr/bin/env python

def main():
    import os, glob
    cached_folder = os.path.expandvars(r'%APPDATA%\Microsoft\Windows\Themes\CachedFiles\*')
    list_of_files = glob.glob(cached_folder)
    print( list_of_files )
    latest_file = max(list_of_files, key=os.path.getctime)
    print( latest_file )
    return

if (__name__ == '__main__' ) :
    main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM