Pergunta

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

Foi útil?

Solução

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)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top