如何在Go中循环遍历文件并将ModTime与日期进行比较?

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

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

huangapple
  • 本文由 发表于 2015年2月24日 03:28:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/28681777.html
匿名

发表评论

匿名网友

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

确定