go read text file into string array

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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 memory11 // 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, err16   }17   defer file.Close()18 19   var lines []string20   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 err32   }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 something4 }5 lines := strings.Split(string(content), "\n")

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.