In a directory I have lots of files. I want to search the most recent file with "dog" in the name, all extension.

path = 'my_path'
name = 'dog'
files = sorted([f for f in os.listdir(path) if f.????(name)])
recent = files[-1]
print "The most recent file with 'dog' in the name is :", recent

Thanks

有帮助吗?

解决方案

This is one way you could do it:

files = sorted((f for f in os.listdir(path) if f.find(name) != -1), 
               key=lambda f: os.stat(os.path.join(path, f)).st_mtime)
recent = files[-1]

sorted takes an optional argument, key, which specifies a function of one argument that returns the key that will be used for sorting. The lambda expression above sorts the array by mtime (last modification time). Credit goes to this answer for the lambda.

If you prefer not to use a lambda, you could also just use a normal function:

def mtime(f): 
    return os.stat(os.path.join(path, f)).st_mtime

files = sorted((f for f in os.listdir(path) if f.find(name) != -1), key=mtime)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top