• go read text file into string array


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

    方法一

     1 package main
     2 
     3 import (
     4   "bufio"
     5   "fmt"
     6   "log"
     7   "os"
     8 )
     9 
    10 // readLines reads a whole file into memory
    11 // and returns a slice of its lines.
    12 func readLines(path string) ([]string, error) {
    13   file, err := os.Open(path)
    14   if err != nil {
    15     return nil, err
    16   }
    17   defer file.Close()
    18 
    19   var lines []string
    20   scanner := bufio.NewScanner(file)
    21   for scanner.Scan() {
    22     lines = append(lines, scanner.Text())
    23   }
    24   return lines, scanner.Err()
    25 }
    26 
    27 // writeLines writes the lines to the given file.
    28 func writeLines(lines []string, path string) error {
    29   file, err := os.Create(path)
    30   if err != nil {
    31     return err
    32   }
    33   defer file.Close()
    34 
    35   w := bufio.NewWriter(file)
    36   for _, line := range lines {
    37     fmt.Fprintln(w, line)
    38   }
    39 
    40 }

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

    1 content, err := ioutil.ReadFile(filename)
    2 if err != nil {
    3     //Do something
    4 }
    5 lines := strings.Split(string(content), "
    ")
  • 相关阅读:
    Python数据结构与算法—栈
    var_export 和 var_dump
    PHp 下标是 区分大小写的
    和眼睛相处
    css 3 animation
    background-attachment: fixed | attachment 区别
    js 函数表达和函数声明
    function 和 new Function
    lastIndexOf js
    substring substr slice js比较
  • 原文地址:https://www.cnblogs.com/yanlixin/p/4732732.html
Copyright © 2020-2023  润新知