按行写数据到csv文件中

package main

import (
	"bufio"
	"encoding/csv"
	"fmt"
	"io"
	"os"
	"strings"
)

func main() {
	f, err := os.Open("new.txt")
	if err != nil {
		panic(err)
	}
	defer f.Close()

	rd := bufio.NewReader(f)

	f2, err2 := os.Create("data.csv")
	if err2 != nil {
		panic(err2)
	}
	defer f2.Close()

	//f2.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM
	w := csv.NewWriter(f2)

	var header = []string{"Time", "cpu"}
	w.Write(header)

	for {
		line, err := rd.ReadString('\n') //以'\n'为结束符读入一行

		if err != nil || io.EOF == err {
			break
		}
		s := strings.Split(strings.TrimSpace(line), " ")
		fmt.Println(s[1], s[2])
		w.Write([]string{s[1], s[2]})

	}
	// 将缓存中的内容写入到文件里
	w.Flush()
}

  

posted on 2022-01-07 11:00  清明-心若淡定  阅读(142)  评论(0编辑  收藏  举报