doukun5339 2015-02-23 19:28
浏览 87
已采纳

前往:如何循环浏览文件并将ModTime与日期进行比较?

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条回答 默认 最新

  • doushaiyu5065 2015-02-23 19:36
    关注

    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
    ", info.Name(), diff)
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ADS生成的微带线为什么是蓝色空心的
  • ¥15 求一下解题思路,完全不懂
  • ¥15 tensorflow
  • ¥15 densenet网络结构中,特征以cat方式复用后是怎么进行误差回传的
  • ¥15 STM32G471芯片spi设置了8位,总是发送16位
  • ¥15 R语言并行计算beta-NTI中tree文件的类型
  • ¥15 如何解读marsbar导出的ROI数据?
  • ¥20 求友友协助弄一下基于STC89C52单片机的声光控制灯原理图
  • ¥15 arduino双向交通灯设计
  • ¥15 有没有会粒子群算法的大能(○゜ε^○)求带不会出收敛图😭