英文:
How to Iterate through directory, ordered based on the file time
问题
Go提供了一个开箱即用的目录迭代功能,使用path/filepath
包中的filepath.Walk
函数。
然而,filepath.Walk
函数按照词法顺序遍历文件树。我该如何按照最后修改日期的顺序遍历文件树?谢谢。
附注(接受答案后)我认为Go的filepath.Walk
函数应该提供一种让用户自己排序的方式,就像下面的答案一样,接受type ByModTime
就足够让用户自己对文件进行排序了。
英文:
Go provides a directory iteration functionality out of the box, with filepath.Walk
in the path/filepath
package.
However, filepath.Walk
walks the file tree in lexical order. How can I walks the file tree in the order of last-modified date? Thx
PS (after accepting the answer) I think the Go filepath.Walk
function should provide a way for people to provide the sorting themselves, like the following answer, in which accepting type ByModTime
is all it take for people to sort the files themselves themselves.
答案1
得分: 7
我认为你应该自己实现它,因为filepath.Walk
不允许你设置顺序。
看一下Walk方法。它调用了walk,它依赖于readDirNames中的文件名。所以基本上,你应该使用另一种readDirNames
逻辑来创建自己的Walk
方法。
以下是按最后修改日期顺序获取文件的示例代码(注意,我忽略了错误):
package main
import (
"fmt"
"os"
"sort"
)
type ByModTime []os.FileInfo
func (fis ByModTime) Len() int {
return len(fis)
}
func (fis ByModTime) Swap(i, j int) {
fis[i], fis[j] = fis[j], fis[i]
}
func (fis ByModTime) Less(i, j int) bool {
return fis[i].ModTime().Before(fis[j].ModTime())
}
func main() {
f, _ := os.Open("/")
fis, _ := f.Readdir(-1)
f.Close()
sort.Sort(ByModTime(fis))
for _, fi := range fis {
fmt.Println(fi.Name())
}
}
英文:
I think, you should implement it by yourself, because filepath.Walk
doesn't allow you to set order.
Look at Walk method. It calls walk, which is relying on file names from readDirNames. So basically, you should make your own Walk
method with another readDirNames
logic.
Here's how you get files in the order of last-modified date (note, that I'm ignoring errors):
package main
import (
"fmt"
"os"
"sort"
)
type ByModTime []os.FileInfo
func (fis ByModTime) Len() int {
return len(fis)
}
func (fis ByModTime) Swap(i, j int) {
fis[i], fis[j] = fis[j], fis[i]
}
func (fis ByModTime) Less(i, j int) bool {
return fis[i].ModTime().Before(fis[j].ModTime())
}
func main() {
f, _ := os.Open("/")
fis, _ := f.Readdir(-1)
f.Close()
sort.Sort(ByModTime(fis))
for _, fi := range fis {
fmt.Println(fi.Name())
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论