Walk a directory/Recursively: Difference between revisions

Content added Content deleted
(→‎{{header|Python}}: put back fnmatch,filter and add a link to its explanation)
(→‎{{header|Go}}: update required for library change. I also made the solution conform better to the task requirement to match a pattern)
Line 827: Line 827:
)
)


func VisitFile(fp string, fi *os.FileInfo, err os.Error) os.Error {
type MyVisitor struct{} // a type to satisfy filepath.Visitor interface
if err != nil {

fmt.Println(err) // can't walk here,
func (MyVisitor) VisitDir(string, *os.FileInfo) bool {
return nil // but continue walking elsewhere
return true
}
}
if !fi.IsRegular() {

return nil // not a file. ignore.
func (MyVisitor) VisitFile(fp string, _ *os.FileInfo) {
}
if filepath.Ext(fp) == ".mp3" {
matched, err := filepath.Match("*.mp3", fi.Name)
if err != nil {
fmt.Println(err) // malformed pattern
return err // this is fatal.
}
if matched {
fmt.Println(fp)
fmt.Println(fp)
}
}
return nil
}
}


func main() {
func main() {
filepath.Walk("/", MyVisitor{}, nil)
filepath.Walk("/", VisitFile)
}</lang>
}</lang>