如何按文件时间顺序遍历目录?

huangapple go评论154阅读模式
英文:

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())
	}
}

huangapple
  • 本文由 发表于 2017年6月6日 09:28:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/44380054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定