Given a list of FileInfo objects, how do I sort them by date? Specifically I want to sort them by CreationTime in descending order.
+1
A:
DirectoryInfo.GetFiles() returns an array of FileInfo objects. I created a generic list to hold the FileInfo objs, and sorted using a custom comparer.
logDir = r"C:\temp"
fileInfosArray = DirectoryInfo(logDir).GetFiles("*.log")
fileInfosList = List[FileInfo]()
fileInfosList.AddRange(fileInfosArray)
fileInfosList.Sort(FileInfoCompareCreationTimeDesc)
for fileInfo in fileInfosList:
print fileInfo.CreationTime, fileInfo.LastAccessTime, fileInfo.LastWriteTime, fileInfo.Name
# comparison delegate for FileInfo objects: sort by CreationTime Descending
def FileInfoCompareCreationTimeDesc(fileInfo1, fileInfo2):
return fileInfo2.CreationTime.CompareTo(fileInfo1.CreationTime)
Tom E
2009-03-04 19:23:31
+2
A:
The Pythonic way of doing this would be:
fileInfos = list(DirectoryInfo(path).GetFiles())
fileInfos.sort(key=lambda f: f.CreationTime, reverse=True)
The list sort method takes a key function that is used to get the sort key for each item.
wilberforce
2009-03-04 23:37:52