how to sort list of FileInfo in IronPython

落花浮王杯 提交于 2019-12-24 10:56:18

问题


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:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/612028/how-to-sort-list-of-fileinfo-in-ironpython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!