Skip to content

Instantly share code, notes, and snippets.

@AndreiD
Last active May 26, 2018 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndreiD/84245c3db5417c560cf81ddd069d67a2 to your computer and use it in GitHub Desktop.
Save AndreiD/84245c3db5417c560cf81ddd069d67a2 to your computer and use it in GitHub Desktop.
Go Golang flatten directory -> read a directory of directories and extract files to another directory
package main
import (
"path/filepath"
"os"
"fmt"
)
const target_directory = "C:\\Users\\WHO?\\Documents\\target\\"
const destination_directory = "C:\\Users\\WHO?\\flatten\\"
func main() {
//verify if both directories exist
info, err := os.Stat(target_directory)
if err != nil {
panic(err)
}
if !info.IsDir() {
panic("target_directory could not be found...")
}
info, err = os.Stat(destination_directory)
if err != nil {
panic(err)
}
if !info.IsDir() {
panic("destination_directory could not be found...")
}
fileList := make([]string, 0)
err = filepath.Walk(target_directory, func(path string, f os.FileInfo, err error) error {
fileList = append(fileList, path)
return err
})
if err != nil {
panic(err)
}
for _, file := range fileList {
fi, err := os.Stat(file)
if err != nil {
fmt.Println(err)
}
//only if it's a normal file
if fi.Mode().IsRegular() {
err = os.Rename(file, destination_directory+filepath.Base(file))
if err != nil {
fmt.Println(err)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment