I"m unable to find file.ReadLine role in Go. Ns can figure out just how to quickly write one, however I am just wondering if I"m overlooking other here. How does one read a document line by line?


*

*

In go 1.1 and newer the many simple means to perform this is v a bufio.Scanner. Below is a simple example the reads lines from a file:

package mainimport ( "bufio" "fmt" "log" "os")func main() file, err := os.Open("/path/to/file.txt") if err != nil log.Fatal(err) defer file.Close() scanner := bufio.NewScanner(file) // optionally, resize scanner"s volume for lines over 64K, see next example for scanner.Scan() fmt.Println(scanner.Text()) if err := scanner.Err(); err != nil log.Fatal(err) This is the cleanest way to review from a reader line by line.

You are watching: Golang read file line by line

There is one caveat: Scanner will error through lines much longer than 65536 characters. If you know your line size is better than 64K, usage the Buffer() an approach to rise the scanner"s capacity:

...scanner := bufio.NewScanner(file)const maxCapacity = longLineLen // your required line lengthbuf := make(<>byte, maxCapacity)scanner.Buffer(buf, maxCapacity)for scanner.Scan() {...
share
enhance this answer
follow
edited Jul 2 at 22:13

*

Zach Young
5,48722 gold badges2626 silver- badges4747 bronze badges
answered may 17 "13 in ~ 18:21
*

Stefan ArentzStefan Arentz
32.3k88 yellow badges6565 silver- badges8686 bronze title
6
| display 1 more comment
168
NOTE: The accepted answer to be correct in early on versions the Go. See the highest possible voted answer contains the much more recent idiomatic way to achieve this.

There is function ReadLine in package bufio.

Please keep in mind that if the line does not fit into the read buffer, the duty will return an incomplete line. If you desire to always read a entirety line in your regimen by a single call come a function, girlfriend will must encapsulate the ReadLine duty into your own duty which call ReadLine in a for-loop.

bufio.ReadString("\n") isn"t fully equivalent come ReadLine because ReadString is can not to handle the instance when the last line of a file does not end with the newline character.


re-superstructure
improve this answer
monitor
edited Feb 7 "20 in ~ 20:56
*

Samuel Hawksby-Robinson
2,25744 yellow badges2121 silver- badges2525 bronze badges
answered january 6 "12 at 12:55
user811773user811773
8
| display 3 more comments
59

EDIT: together of go1.1, the idiomatic solution is to use bufio.Scanner

I composed up a way to conveniently read every line from a file. The Readln(*bufio.Reader) duty returns a heat (sans \n) from the basic bufio.Reader struct.

// Readln returns a single line (without the finishing \n)// native the input buffered reader.// an error is returned iff over there is one error through the// buffered reader.func Readln(r *bufio.Reader) (string, error) var (isPrefix bool = true err error = nil line, ln <>byte ) because that isPrefix && err == nil line, isPrefix, err = r.ReadLine() ln = append(ln, line...) return string(ln),errYou have the right to use Readln to read every heat from a file. The following code reads every heat in a file and outputs each line come stdout.

f, err := os.Open(fi)if err != nil fmt.Printf("error opening file: %v\n",err) os.Exit(1)r := bufio.NewReader(f)s, e := Readln(r)for e == nil fmt.Println(s) s,e = Readln(r)Cheers!


share
improve this answer
follow
edited Aug 7 "14 at 22:08
answer Aug 30 "12 in ~ 22:37
MalcolmMalcolm
2,16311 yellow badge2222 silver badges2626 bronze title
1
include a comment |
35
There two common method to read record line by line.

See more: Erin Breen: Life Is Like A Game Of Chess Is Like Life, Life Is Like A Chess Game

Use bufio.ScannerUse ReadString/ReadBytes/... In bufio.Reader

In mine testcase, ~250MB, ~2,500,000 lines, bufio.Scanner(time used: 0.395491384s) is faster than bufio.Reader.ReadString(time_used: 0.446867622s).

Source code: https://github.com/xpzouying/go-practice/tree/master/read_file_line_by_line

Read file use bufio.Scanner,

func scanFile() f, err := os.OpenFile(logfile, os.O_RDONLY, os.ModePerm) if err != nil log.Fatalf("open record error: %v", err) return defer f.Close() sc := bufio.NewScanner(f) because that sc.Scan() _ = sc.Text() // obtain the heat string if err := sc.Err(); err != nil log.Fatalf("scan paper error: %v", err) return Read document use bufio.Reader,

func readFileLines() f, err := os.OpenFile(logfile, os.O_RDONLY, os.ModePerm) if err != nil log.Fatalf("open record error: %v", err) return defer f.Close() rd := bufio.NewReader(f) for line, err := rd.ReadString("\n") if err != nil if err == io.EOF break log.Fatalf("read record line error: %v", err) return _ = line // acquire the heat string