{"id":288,"date":"2019-10-19T03:56:42","date_gmt":"2019-10-19T03:56:42","guid":{"rendered":"https:\/\/golangbyexamples.com\/?p=288"},"modified":"2019-11-12T19:38:17","modified_gmt":"2019-11-12T19:38:17","slug":"read-large-file-line-by-line-go","status":"publish","type":"post","link":"https:\/\/golangbyexamples.com\/read-large-file-line-by-line-go\/","title":{"rendered":"Read a large file Line by Line 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. 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 \nline by line.<\/code><\/pre>\n\n\n\nHere is the program:<\/p>\n\n\n\n
package main\nimport (\n \"bufio\"\n \"fmt\"\n \"log\"\n \"os\"\n)\nfunc main(){\n LinebyLineScan()\n}\nfunc LinebyLineScan() {\n file, err := os.Open(\".\/sample.txt\")\n if err != nil {\n log.Fatal(err)\n }\n defer file.Close()\n scanner := bufio.NewScanner(file)\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 is an example\nto show how \nto read file \nline by line.<\/code><\/pre>\n\n\n\nNote 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\n
bufio.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. Let’s say…<\/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":[38,3,39,41,40],"class_list":["post-288","post","type-post","status-publish","format-standard","hentry","category-tech","tag-file","tag-go","tag-largefile","tag-line-by-line","tag-linebyline"],"yoast_head":"\n
Read a large file Line by Line 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