質問

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