문제

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