{"id":292,"date":"2019-10-19T04:06:13","date_gmt":"2019-10-19T04:06:13","guid":{"rendered":"https:\/\/golangbyexamples.com\/?p=292"},"modified":"2019-11-12T19:36:03","modified_gmt":"2019-11-12T19:36:03","slug":"read-large-file-word-by-word-go","status":"publish","type":"post","link":"https:\/\/golangbyexamples.com\/read-large-file-word-by-word-go\/","title":{"rendered":"Read a large file Word by Word in Go(Golang)"},"content":{"rendered":"\n
When it comes to reading large files, obviously we don’t want to load the entire file in memory. bufio package in golang comes to the rescue when reading large files in Golang. Let’s say we have a sample.txt file with below contents<\/p>\n\n\n\n
This is an example\nto show how\nto read file\nword by word.<\/code><\/pre>\n\n\n\nWord by Word scan<\/strong><\/h2>\n\n\n\npackage main\nimport (\n \"bufio\"\n \"fmt\"\n \"log\"\n \"os\"\n)\nfunc main() {\n WordbyWordScan()\n}\nfunc WordbyWordScan() {\n file, err := os.Open(\".\/scanner\/sample.txt\")\n if err != nil {\n log.Fatal(err)\n }\n defer file.Close()\n scanner := bufio.NewScanner(file)\n scanner.Split(bufio.ScanWords)\n for scanner.Scan() {\n fmt.Println(scanner.Text())\n }\n if err := scanner.Err(); err != nil {\n log.Fatal(err)\n }\n}<\/code><\/pre>\n\n\n\nOutput:<\/strong><\/p>\n\n\n\nThis\nis\nan\nexample\nto\nshow\nhow\nto\nread\nfile\nline\nby\nline\nand\nword\nby\nword.<\/code><\/pre>\n\n\n\nPlease note that in the above program we set scanner.Split(bufio.ScanWords)<\/strong> which helps us to read the file word by word. Note however bufio.Scanner has max buffer size 64*1024 bytes which means in case you file has any line greater than the size of 64*1024, then it will give the error <\/p>\n\n\n\nbufio.Scanner: token too long<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"When it comes to reading large files, obviously we don’t want to load the entire file in memory. bufio package in golang comes to the rescue when reading large files in Golang….<\/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-292","post","type-post","status-publish","format-standard","hentry","category-tech"],"yoast_head":"\n
Read a large file Word by Word in Go(Golang) - Welcome To Golang By Example<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n