英文:
Go: How to loop through files and compare ModTime to a date?
问题
我正在尝试遍历目录中的文件,并将它们的修改时间与特定日期进行比较,以便删除旧文件。
我正在使用ioutil.ReadDir()来获取文件,但我不知道如何获取每个文件的修改时间。
谢谢。
英文:
I'm trying to loop through files in a directory and compare their ModTime against a certain date in order to delete older files.
I'm using ioutil.ReadDir() to get the files but I'm stuck with how to retrieve the ModTime of each file.
Thanks
答案1
得分: 10
ioutil.ReadDir
的返回值是([]os.FileInfo, error)
。你只需要遍历[]os.FileInfo
切片,并检查每个文件的ModTime()
。ModTime()
返回一个time.Time
,所以你可以按照任何你认为合适的方式进行比较。
package main
import (
"fmt"
"io/ioutil"
"log"
"time"
)
var cutoff = 1 * time.Hour
func main() {
fileInfo, err := ioutil.ReadDir("/tmp")
if err != nil {
log.Fatal(err.Error())
}
now := time.Now()
for _, info := range fileInfo {
if diff := now.Sub(info.ModTime()); diff > cutoff {
fmt.Printf("Deleting %s which is %s old\n", info.Name(), diff)
}
}
}
请注意,这是一个用Go语言编写的示例代码,用于遍历指定目录下的文件,并删除超过指定时间的文件。
英文:
The return from ioutil.ReadDir
is ([]os.FileInfo, error)
. You would simply iterate the []os.FileInfo
slice and inspect the ModTime()
of each. ModTime()
returns a time.Time
so you can compare in any way you see fit.
package main
import (
"fmt"
"io/ioutil"
"log"
"time"
)
var cutoff = 1 * time.Hour
func main() {
fileInfo, err := ioutil.ReadDir("/tmp")
if err != nil {
log.Fatal(err.Error())
}
now := time.Now()
for _, info := range fileInfo {
if diff := now.Sub(info.ModTime()); diff > cutoff {
fmt.Printf("Deleting %s which is %s old\n", info.Name(), diff)
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论