读取和写入csv文件
package main
import (
"encoding/csv"
"fmt"
"os"
"strconv"
)
type Post struct {
Id int
Content string
Author string
}
func main(){
//使用os包中的Create函数创建csv文件
csvFile,err:=os.Create("posts.csv")
if err!=nil{
panic(err)
}
//使用完后关闭该文件
defer csvFile.Close()
//创建一个Post类型的切片,并给该切片赋4个初值
allPosts:=[]Post{
{Id: 1,Content: "Hello World!",Author: "Sau sheong"},
{Id: 2,Content: "Bonjour Monde",Author: "Pie"},
{Id: 3,Content: "Hole Munfe",Author: "Pei"},
{Id: 4,Content: "Greting Hidnc",Author: "Gut"},
}
//创建一个writer对象,用来调用相应的方法
writer:=csv.NewWriter(csvFile)
//对csv文件进行写操作
for _,post:=range allPosts{
//strconv.Itoa()作用是将int类型的Id转换成string类型
//由于csv包中的writer函数接收的是[]string类型的切片,因此要将allPosts中的各个值进行重新组织
line:=[]string{strconv.Itoa(post.Id),post.Content,post.Author}
err:=writer.Write(line)
if err!=nil{
panic(err)
}
}
//将缓存中的数据写入底层的io.Writer。
writer.Flush()
//用os包中的open函数打开posts.csv文件
file,err:=os.Open("posts.csv")
if err!=nil{
panic(err)
}
//创建reader对象,用来调用相关的读操作
reader:=csv.NewReader(file)
records,err:=reader.ReadAll()
fmt.Println(records)
//对Id进行类型转换
var posts []Post
for _,item:=range records{
id,_:=strconv.ParseInt(item[0],0,0)
post:=Post{
Id: int(id),
Content: item[1],
Author: item[2],
}
posts=append(posts,post)
}
fmt.Println(posts[0])
}
输出结果:
使用gob包对文件编码解码
package main
import (
"bytes"
"encoding/gob"
"fmt"
"io/ioutil"
)
type Post struct {
Id int
Content string
Author string
}
//存储数据
func store(data interface{},filename string){
//builtin包中的new函数:内建函数new分配内存。其第一个实参为类型,而非值。其返回值为指向该类型的新分配的零值的指针。
buffer:=new(bytes.Buffer)
//NewEncoder返回一个将编码后数据写入w的*Encoder。
encoder:=gob.NewEncoder(buffer)
err:=encoder.Encode(data)
if err!=nil{
panic(err)
}
err=ioutil.WriteFile(filename,buffer.Bytes(),0600)
if err!=nil{
panic(err)
}
}
//载入数据
func load(data interface{},filename string){
raw,err:=ioutil.ReadFile(filename)
if err!=nil{
panic(err)
}
buffer:=bytes.NewBuffer(raw)
dec:=gob.NewDecoder(buffer)
err=dec.Decode(data)
if err!=nil{
panic(err)
}
}
func main(){
post:=Post{
Id: 1,
Content: "Hello World!",
Author: "Sau Sheong",
}
store(post,"post1")
var postRead Post
load(&postRead,"post1")
fmt.Println(postRead)
}
工作流程