惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
G
Google Developers Blog
aimingoo的专栏
aimingoo的专栏
罗磊的独立博客
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
D
Docker
博客园 - 三生石上(FineUI控件)
博客园 - 司徒正美
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
月光博客
月光博客
S
SegmentFault 最新的问题
Jina AI
Jina AI
Blog — PlanetScale
Blog — PlanetScale
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - Franky
L
LangChain Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Microsoft Azure Blog
Microsoft Azure Blog
阮一峰的网络日志
阮一峰的网络日志
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Last Week in AI
Last Week in AI

博客园 - π三毛

Hyperledge 开发环境配置常见问题 SQL Server 2012日志文件误删除数据库质疑后的相关恢复 mac boot2docker certs not valid with 1.7 T-SQL 比较N个指段取其中最大值 xcode-git笔记 如何定位Sharepoint网站集所在的w3wp进程 node常用包 Google analytics Offline Installation the .NET Framework 3.5 on Windows 8 [MSDN]How to use the computer keyboard with Windows Phone Emulator Managing SharePoint 2010 Farm Solutions with Windows PowerShell turning on full error Messages [转]vi使用方法 转帖-在oracle中自动大批量生成测试数据 删除大恒文档加密客户端 Terminating the Session with ALTER SYSTEM Oracle RMAN vs. Export? 错误14274:无法添加、更新或删除从msx服务器上发起的作业(或其步骤或调度) MS SQL SERVER 2000 同步计算机名称
go read text file into string array
π三毛 · 2015-08-15 · via 博客园 - π三毛

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")