登录
首页 >  Golang >  Go问答

获取文件路径在Golang中的操作

来源:stackoverflow

时间:2024-02-16 11:00:24 466浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《获取文件路径在Golang中的操作》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

问题内容

我需要读取目录中的所有文件,结构如下:

/data
   /folder1
     somefiles.txt
   /folder2
     /folder2.1
       somefiles.txt
   /folder3
       somefiles.txt
    ...

我尝试了 walk 方法,但是 walk 会读取文件,当文件处理完毕后,它会删除信息并继续处理下一个文件。我确实需要将其与所有数据一起保存在一个对象中(我正在使用地图切片),因为我需要使用 api 端点,并且当我插入大量数据时,它比逐一插入要快(在目录内)有数千个文件,所以一个一个地需要很多时间)

我的想法是做一个递归函数(比如 walk),但我不知道如何知道文件路径,或者我不知道是否可以使用 walk 函数内的指针访问(我对 go 真的很陌生)并将文件数据保存在全局变量或类似的变量中


正确答案


要使用 fs.walkdir(),您只需让处理程序关闭在 fs.walkdir() 执行完成时需要填充的变量。

例如,这会递归地遍历指定的目录树。目录被忽略。填充 map[string][]byte,以每个文件的完全限定路径为键,包含每个文件的内容。

package main

import (
  "fmt"
  "io/fs"
  "os"
  "path"
  "path/filepath"
  // "path"
)

func main() {
  root := "/path/to/root/directory"

  files := map[string][]byte{}

  handler := func(p string, d fs.DirEntry, err error) error {

    switch {
    case err != nil:
      return err
    case shouldSkipDir(p, d):
      return fs.SkipDir
    case d.IsDir():
      return nil
    case shouldSkipFile(p, d):
      return nil
    default:
      if fqn, e := filepath.Abs(path.Join(root, p)); e != nil {
        return e
      }
      buf, e := os.ReadFile(fqn)
      if e != nil {
        return e
      }
      files[fqn] = buf
    }

    return nil
  }

  err := fs.WalkDir(os.DirFS(root), ".", handler)
  if err != nil {
    panic(err)
  }

  for fqn, contents := range files {
    fmt.Printf("%s: %d bytes", fqn, len(contents))
  }

}

func shouldSkipDir(path string, d fs.DirEntry) (skip bool) {
  // TODO: set skip to true to indicate that this directory should be skipped.
  // If the current direcotry entry is a file and this returns true, then
  // the remainder of its containing directory are skipped.
  return skip
}

func shouldSkipFile(path string, d fs.DirEntry) (skip bool) {
  // TODO: set skip to true to ignore this file
  return skip
}

今天关于《获取文件路径在Golang中的操作》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>