B
B
beduin012018-07-08 15:25:54
go
beduin01, 2018-07-08 15:25:54

How to list all files with txt and csv extension?

Here is an example of how to list all files with csv and txt extension?
Here is the code to bypass all files:

package main

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

func main() {
    var files []string

    root := "/some/folder/to/scan"
    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        files = append(files, path)
        return nil
    })
    if err != nil {
        panic(err)
    }
    for _, file := range files {
        fmt.Println(file)
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Burov, 2018-07-08
@BuriK666

err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
    if !info.IsDir() {
      ext := filepath.Ext(path)
      if ext == ".txt" || ext == ".csv" {
        files = append(files, path)
      }
    }
    return nil
  })

S
SergeySlukin, 2018-07-08
@SergeySlukin

I'm just learning Go myself, I wanted to do this

if !info.IsDir() {
      fileLen := len(info.Name())
      if info.Name()[fileLen - 4:] == ".csv" || info.Name()[fileLen - 4:] == ".txt" {
        files = append(files, path)
      }
    }

The option proposed by Andrey Burov is more correct.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question