Skip to content

Instantly share code, notes, and snippets.

@ShawnMilo
Last active August 29, 2015 13:57
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 ShawnMilo/9727816 to your computer and use it in GitHub Desktop.
Save ShawnMilo/9727816 to your computer and use it in GitHub Desktop.
package main
// Delete *.pyc files.
// Basically does this:
// find . -name '*.pyc' -exec rm {} \;
import (
"log" // for writing errors and quitting if something breaks
"os" // for command-line args and getting file info
"path/filepath" // for walking a directory tree
"strings" // for checking filename substrings
)
// main reads the command-line args and kicks off
// the walk through the directory tree, using the custom WalkFunc.
func main() {
var dir string
var err error
if len(os.Args) > 1 {
dir = os.Args[1]
} else {
dir, err = os.Getwd()
if err != nil {
log.Fatal("Couldn't get current directory.")
}
}
// Sanity check.
if dir == "" {
log.Fatal("Couldn't determine working directory.")
}
stat, err := os.Stat(dir)
if err != nil {
log.Fatal(err)
}
if stat.IsDir() == false {
log.Fatal(dir, " is not a directory.")
}
filepath.Walk(dir, hunt)
}
// hunt is a WalkFunc, as defined in path/filepath.
func hunt(path string, info os.FileInfo, err error) error {
if strings.HasSuffix(path, ".pyc") {
err := os.Remove(path)
// Make noise, but don't kill the whole program.
if err != nil {
log.Println(err)
}
}
return nil
}
@ShawnMilo
Copy link
Author

Updated recently to remove concurrency, since it was unnecessary and sometimes led to the program exiting before all files were deleted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment