码迷,mamicode.com
首页 > 其他好文 > 详细

009-Go 读取写入CSV文件

时间:2018-06-03 23:29:26      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:UNC   content   ack   create   value   encoding   print   IV   dsp   

package main

import(
	"encoding/csv"
	"fmt"
	"os"
	"strconv"
)

type Post struct{
	Id	int
	Content	string
	Author	string
}

func main(){
	csvFile, err := os.Create("posts.csv")
	if err!= nil{
		panic(err)
	}
	defer csvFile.Close()

	posts := []Post{
		Post{Id:100,Content:"Hello go",Author:"张三"},
		Post{Id:200,Content:"Hello java",Author:"李四"},
		Post{Id:300,Content:"Hello php",Author:"王五"},
	}

	writer := csv.NewWriter(csvFile)
	for _,post := range posts{
		line := []string{strconv.Itoa(post.Id), post.Content, post.Author}
		err := writer.Write(line)
		if err != nil{
			panic(err)
		}
	}
	writer.Flush()

	file,err := os.Open("posts.csv")
	if err != nil{
		panic(err)
	}
	defer file.Close()

	reader := csv.NewReader(file)
	reader.FieldsPerRecord = -1
	record, err := reader.ReadAll()
	if err != nil{
		panic(err)
	}

	var myposts []Post
	for _, item := range record{
		id, _ := strconv.ParseInt(item[0], 0, 0)
		post := Post{Id: int(id), Content:item[1], Author:item[2]}
		myposts = append(myposts, post)
	}

	for _, value := range myposts{
		fmt.Printf("Id:%d,Content:%s,Author:%s\n", value.Id, value.Content, value.Author)
	}

}

  

009-Go 读取写入CSV文件

标签:UNC   content   ack   create   value   encoding   print   IV   dsp   

原文地址:https://www.cnblogs.com/yshyee/p/9130989.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!