Golang Read File Line by Line

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
func handle(textfile string) error {
    // 1. open file
    file, err := os.Open(textfile)
	if err != nil {
		log.Printf("Cannot open text file: %s, err: [%v]", textfile, err)
		return err
	}
    defer file.Close()
    //2. new a scanner to scan file
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
		line := scanner.Text() // or
		//line := scanner.Bytes()
		
        // do somthing
		fmt.Printf("%s\n", line)
	}

	if err := scanner.Err(); err != nil {
		log.Printf("Cannot scanner text file: %s, err: [%v]", textfile, err)
		return err
	}

	return nil
}