日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

go read text file into string array

發(fā)布時(shí)間:2025/3/15 编程问答 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 go read text file into string array 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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), "\n")

?

轉(zhuǎn)載于:https://www.cnblogs.com/yanlixin/p/4732732.html

總結(jié)

以上是生活随笔為你收集整理的go read text file into string array的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。