{"id":1166,"date":"2020-01-16T04:53:33","date_gmt":"2020-01-16T04:53:33","guid":{"rendered":"https:\/\/golangbyexamples.com\/?p=1166"},"modified":"2021-04-22T19:38:01","modified_gmt":"2021-04-22T14:08:01","slug":"iterate-over-all-files-and-folders-go","status":"publish","type":"post","link":"https:\/\/golangbyexamples.com\/iterate-over-all-files-and-folders-go\/","title":{"rendered":"Iterate over all files and folders for a path in Go (Golang)"},"content":{"rendered":"\n
‘Walk’<\/strong> function of ‘filepath’<\/strong> package can be used to recursively iterate over all files\/folder in a directory tree.<\/p>\n\n\n\n ‘Walk’<\/strong> function will walk the entire tree rooted at the root path include all subdirectories. Below is the signature of the function<\/p>\n\n\n\n The WalkFunc will be called for with the path<\/strong> of the file\/folder and fileInfo<\/strong> or the error<\/strong> if any error occurred while walking that file\/folder.<\/p>\n\n\n\n Some things to note about Walk function<\/p>\n\n\n\n Let’s see an example:<\/p>\n\n\n\n ‘Walk’ function of ‘filepath’ package can be used to recursively iterate over all files\/folder in a directory tree. ‘Walk’ function will walk the entire tree rooted at the root path include all…<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","footnotes":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[1],"tags":[],"class_list":["post-1166","post","type-post","status-publish","format-standard","hentry","category-tech"],"yoast_head":"\nhttps:\/\/golang.org\/pkg\/path\/filepath\/<\/code><\/pre>\n\n\n\n
type WalkFunc func(path string, info os.FileInfo, err error) error<\/code><\/pre>\n\n\n\n
package main\n\nimport (\n \"fmt\"\n \"log\"\n \"os\"\n \"path\/filepath\"\n)\n\nfunc main() {\n currentDirectory, err := os.Getwd()\n if err != nil {\n log.Fatal(err)\n }\n iterate(currentDirectory)\n}\n\nfunc iterate(path string) {\n filepath.Walk(path, func(path string, info os.FileInfo, err error) error {\n if err != nil {\n log.Fatalf(err.Error())\n }\n fmt.Printf(\"File Name: %s\\n\", info.Name())\n return nil\n })\n}<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"