Monday, April 11, 2011

how to sort list of FileInfo in IronPython

Given a list of FileInfo objects, how do I sort them by date? Specifically I want to sort them by CreationTime in descending order.

From stackoverflow
  • 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)
    
  • 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.

0 comments:

Post a Comment