go read text file into string array

时间:2021-01-19 22:50:19

http://*.com/questions/5884154/golang-read-text-file-into-string-array-and-write

方法一

 package main

 import (
"bufio"
"fmt"
"log"
"os"
) // readLines reads a whole file into memory
// and returns a slice of its lines.
func readLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close() var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
} // writeLines writes the lines to the given file.
func writeLines(lines []string, path string) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close() w := bufio.NewWriter(file)
for _, line := range lines {
fmt.Fprintln(w, line)
} }

方法二(比较简洁,但文件不能太大)

 content, err := ioutil.ReadFile(filename)
if err != nil {
//Do something
}
lines := strings.Split(string(content), "\n")