dsfjnxjlbqv9812 2017-08-08 21:18
浏览 379
已采纳

Golang按日期和时间查找最新文件

I am not sure if I am doing this correctly, but ultimately I would like to find the most recent modified date of a file in a directory and return the file name. The code I have so far is as follows. Can someone please help me with a more efficient solution than this. I really have a feeling this is super hacky. What I am doing is getting the dates and removing the

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "strconv"
    "strings"
)

func main() {
    dir := "C:\\temp\\"
    files, _ := ioutil.ReadDir(dir)
    for _, f := range files {
        fi, _ := os.Stat(dir + f.Name())
        s := strings.Split(fi.ModTime().Format("2006-01-02 15.04.05.000"), " ")

        fdate, err := strconv.Atoi(strings.Replace(s[0], "-", "", -1))
        if err != nil {
            fmt.Println(err)
        }

        ftime, err := strconv.Atoi(strings.Replace(s[1], ".", "", -1))
        if err != nil {
            fmt.Println(err)
        }
        fmt.Println(fi.Name(), fdate+ftime)
    }

}
  • 写回答

2条回答 默认 最新

  • douhoushou8385 2017-08-08 22:52
    关注

    Pay attention to details and efficiency. Check for errors. You asked for files so skip directories and other things. Allow for multiple files with the same modified time stamp (for example, Windows file times have a resolution of, at best, 100-nanoseconds). You already have ModTime() so don't call os.Stat(). Use time.Time methods directly. And so on.

    For example,

    package main
    
    import (
        "fmt"
        "io/ioutil"
        "os"
        "time"
    )
    
    func main() {
        dir := `C:\temp\` // Windows directory
        files, err := ioutil.ReadDir(dir)
        if err != nil {
            fmt.Fprintln(os.Stderr, err)
            os.Exit(1)
        }
        var modTime time.Time
        var names []string
        for _, fi := range files {
            if fi.Mode().IsRegular() {
                if !fi.ModTime().Before(modTime) {
                    if fi.ModTime().After(modTime) {
                        modTime = fi.ModTime()
                        names = names[:0]
                    }
                    names = append(names, fi.Name())
                }
            }
        }
        if len(names) > 0 {
            fmt.Println(modTime, names)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化