Last active
May 26, 2018 18:04
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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