Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Glob search files in date order?

I have this line of code in my python script. It searches all the files in in a particular directory for * cycle *.log.

for searchedfile in glob.glob("*cycle*.log"): 

This works perfectly, however when I run my script to a network location it does not search them in order and instead searches randomly.

Is there a way to force the code to search by date order?

This question has been asked for php but I am not sure of the differences.

Thanks

like image 508
Jason Rogers Avatar asked May 02 '14 14:05

Jason Rogers


People also ask

Does glob search recursively?

Using Glob() function to find files recursivelyWe can use the function glob. glob() or glob. iglob() directly from glob module to retrieve paths recursively from inside the directories/files and subdirectories/subfiles.

How do you get a directory listing sorted by creation date in Python?

To get a directory listing sorted by creation date in Python, you can call os. listdir() to get a list of the filenames. Then call os. stat() for each one to get the creation time and finally sort against the creation time.


Video Answer


2 Answers

To sort files by date:

import glob import os  files = glob.glob("*cycle*.log") files.sort(key=os.path.getmtime) print("\n".join(files)) 

See also Sorting HOW TO.

like image 61
jfs Avatar answered Oct 08 '22 11:10

jfs


Essentially the same as @jfs but in one line using sorted

import os,glob searchedfiles = sorted(glob.glob("*cycle*.log"), key=os.path.getmtime) 
like image 25
Pablo Reyes Avatar answered Oct 08 '22 09:10

Pablo Reyes