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
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.
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.
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.
Essentially the same as @jfs but in one line using sorted
import os,glob searchedfiles = sorted(glob.glob("*cycle*.log"), key=os.path.getmtime)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With