009-Go 读取写入CSV文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | 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) } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步