dongtuliao6760 2017-08-29 14:32
浏览 262
已采纳

如何在Go中获取目录中所有文件的完整路径?

I am using Go to iterate over all the files in a directory. This is how I am doing it:

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    printFiles(".")
}

func printFiles(dir string) {
    fileInfos, err := ioutil.ReadDir(dir)
    if err != nil {
        fmt.Println("Error in accessing directory:", err)
    }

    for _, file := range fileInfos {
        fmt.Printf("%T: %+v
", file, file)
    }
}

When I run this code, this is the output I get:

*os.fileStat: &{name:main.go sys:{FileAttributes:32 CreationTime:{LowDateTime:2993982878 HighDateTime:30613689} LastAccessTime:{LowDateTime:2993982878 HighDateTime:30613689} LastWriteTime:{LowDateTime:4004986069 HighDateTime:30613714} FileSizeHigh:0 FileSizeLow:320} pipe:false Mutex:{state:0 sema:0} path:C:\Users\Prakhar.Mishra\go\src\mistdatafilter\main.go vol:0 idxhi:0 idxlo:0}

I can see a property named path, but I can't access it (due to small case initial, I suppose?). Can anyone please tell me how to get full file path of all the files in a given folder?

  • 写回答

1条回答 默认 最新

  • dqwh2717 2017-08-29 14:35
    关注

    If you want to see a full path, you should start with a full path. . is a relative path.

    You can get the working path with os.Getwd

    path, err := os.Getwd()
    // handle err
    printFiles(path)
    

    The rest is simply appending the file name to the directory path. You should use the path/filepath package for that:

    for _, file := range fileInfos {
        fmt.Println(filepath.Join(path, file.Name())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求指导ADS低噪放设计
  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存