drls2738 2018-05-17 06:35
浏览 23

如何遍历特定文件夹

I have following directory structure

Root
   |
   |-- dev 
   |     | 
   |     +- files, subdirectory within dev
   |-- prod
   |     |
   |     +- files, subdirectory within prod 
   |-- .git
   |     |
   |     +- .git directory structure
   |--CODEOWNER (file)
   |--README (file)

I want to traverse all files in dev and prod.

I tried doing the following

files, err := ioutil.ReadDir("./")
if err != nil {
    log.Fatal(err)
}

for _, val := range files {
    // To handle codeowner and readme
    if !val.isDir(){
       continue
    }

   // To handle .git
   if val.Name() == ".git"{
     continue
   }
    err := filepath.Walk(val, func(path string, f os.FileInfo, err error) error {
     // Traverse dircectory , subdirectories and files
}

Is there any better way of doing this? My only requirement is "I want to traverse top-level directory(dev and prod) in root directory other than directory starting with a dot(.)

To be more clear:

  • In output I want
    • All files, directories, subdirectories of dev
    • All files, directories, subdirectories of prod
  • what I do not want
    • Any director of root other than dev and prod (like .git)
    • Any files of root (like codeowner or readme)
  • 写回答

1条回答 默认 最新

  • dsfhe34889789708 2018-05-17 07:43
    关注

    Use filepath.Glob.

    This gets all files in the foo directory, relative to your working directory:

    matches, err := filepath.Glob("./foo/*")
    if err != nil {
        panic(err.Error())
    }
    
    for _, match := range matches {
        fmt.Printf("Got match: %s
    ", match)
    }
    

    Playground

    In your case, you'd use filepath.Glob("./dev/*") and filepath.Glob("./prod/*"). Go's implementation doesn't support the "double-star directive" for recursive globs though, so you will have to handle subdirectories yourself.

    评论

报告相同问题?

悬赏问题

  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思